C++输入问题
using namespace std;#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
int c = 0;
string x;
cin >> n;
vector<string> strings1;
for (int i = 1; i <= n; i++)
{
getline(cin, x);
strings1.push_back(x);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < strings1.size(); j++)
{
if (strings1 == ' ')
{
cout << '0' << endl;
c = 1;
break;
}
}
if (c == 1)
{
continue;
}
if (strings1 == '_' || isalpha(strings1))
{
cout << '1' << endl;
}
else
{
cout << '0' << endl;
}
}
return 0;
}为什么第一个输入的n也进入了vector 在这段代码中,第一个输入的n也进入了vector的原因是因为在使用cin读取n之后,换行符'\n'仍然留在输入缓冲区中。当使用getline函数读取字符串时,它会读取输入缓冲区中的换行符,并将其作为一个空字符串""读取到变量x中。然后,这个空字符串会被添加到vector strings1中。
为了解决这个问题,我们可以在读取n之后,使用cin.ignore()函数来清除输入缓冲区中的换行符。修改代码如下:
#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
int c = 0;
std::string x;
std::cin >> n;
std::cin.ignore(); // 清除输入缓冲区中的换行符
std::vector<std::string> strings1;
for (int i = 1; i <= n; i++)
{
getline(std::cin, x);
strings1.push_back(x);
}
// 其他代码...
return 0;
}
通过在读取n之后调用cin.ignore()函数,我们清除了输入缓冲区中的换行符,确保它不会被getline函数读取到变量x中。这样,第一个输入的n就不会进入vector strings1了。
页:
[1]