getline,cin,ignore
getline:可读入包含空格在内的字符串,以回车作为结束符,输入完回车之后缓存区内的第一个字符为回车;
cin:以读入缓存区内的字符,以空白符作为结束(eg:空格符,回车符)
ignore(int n,int d):跳过n个字符,在n个字符之前有d则提前结束,无参时跳过一个字符
之前学习的时候定义一个字符串s再用函数getline(cin, s)可以读取一个到换行符结束的字符串,但是今天做的联系中这个函数却被自动忽略了。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a;
string s;
cout << "choose 1, 2 or 3" << endl
<< "1. copy a string" << endl
<< "2. size of a string" << endl
<< "3. size of a line" << endl;
cin >> a;
if (a != 1 & a != 2 & a != 3) cout << "ERROR!" << endl;
else {
if (a == 1)
{
cout << "Enter a string : ";
cin >> s;
cout << s << endl;
} else if (a == 2) {
cout << "Enter a string : ";
cin >> s;
cout << "The size of " << s << " is " << s.size()
<< " characters, including the newline" << endl;
}
else {
cout << "Enter a string : ";
getline(cin,s);
cout << "The size of " << s << " is " << s.size()
<< " characters, including the newline" << endl;
}
}
return 0;
}
当a赋值为1和2时都没问题,但当a赋值为3时,运行结果为:
choose 1, 2 or 3
1. copy a string
2. size of a string
3. size of a line
3 (这里是我输入的3)
Enter a string : The size of is 0 characters, including the newline
在输出 Enter a string :后自动跳过getline函数,直接把s赋值为了一个空字符串,这是为什么呢?
但当我在getline(cin, s);这句后再加一句getline(cin, s);就运行正常了。在提示输入字符串的时候给我输入的机会了,为撒?
错哪儿了?如何改正?