这是我的原始代码:
#include <iostream>
void printArrayValues(int x, int y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
int myArray[2];
std::cout << "Please enter what you want the first element in 'myArray' to be: ";
std::cin >> myArray[0] >> std::endl;
std::cout << "Please enter what you want the second element in 'myArray' to be: ";
std::cin >> myArray[1] >> std::endl;
printArrayValues(myArray[0], myArray[1]);
return 0;
}
我查了我的错误,它说这是因为我没有#include <string>
。我对此感到困惑,因为没有声明字符串,但我还是继续#include
了它。它似乎已经修复了它,但是当我回来时,同样的错误又回来了。这是我的新代码:
#include <fstream>
#include <iostream>
#include <istream>
#include <string>
void printArrayValues(int x, int y)
{
std::cout << x << std::endl;
std::cout << y << std::endl;
}
int main()
{
int myArray[2];
std::cout << "Please enter what you want the first element in 'myArray' to be: ";
std::cin >> myArray[0] >> std::endl;
std::cout << "Please enter what you want the second element in 'myArray' to be: ";
std::cin >> myArray[1] >> std::endl;
printArrayValues(myArray[0], myArray[1]);
return 0;
}
错误仍然显示,因此仍未修复,我不确定该怎么办。有人可以告诉我如何修复它并解释为什么该特定修复有效吗?谢谢!
std::cin >> myArray[0] >> std::endl;
不正确。std::endl
仅适用于输出流。例:
std::cout << myArray[0] << std::endl;
如果要跳过换行符的所有内容,请使用std::istream::ignore()
1。
std::cin >> myArray[0];
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
但是,在您的情况下,您不需要它,因为默认情况下operator>>
会忽略前导空格(除非您使用std::noskipws
(,包括换行符。您可以简单地使用:
std::cout << "Please enter what you want the first element in 'myArray' to be: ";
std::cin >> myArray[0];
std::cout << "Please enter what you want the second element in 'myArray' to be: ";
std::cin >> myArray[1];
1:如果您决定使用std::cin.ignore()
,请添加
#include <limits>
得到std::numeric_limits
的定义。