我正在编写一个简单的代码来了解更多关于字符串的信息。当我运行我的代码时,它不会打印我的姓氏。有人能解释一下原因吗?我使用字符串短语来存储它,它似乎只存储了我的名字。代码如下:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
我使用字符串短语来存储它,它似乎只存储了我的名字。
有道理。
cin >> phrase;
当在输入中遇到空白字符时,它将停止读取。
要读取全名,可以使用以下方法之一:
使用两次呼叫
cin >>
std::string first_name; std::string last_name; cin >> first_name >> last_name;
使用
getline
读取整行。getline
将读取一行中的所有内容,包括空白字符。getline(cin, phrase);
当您调用cin >> phrase;
时,它只读取字符串直到第一个非空格字符。如果您想在名称中包含空格,最好使用getline(cin,phrase);
。
重要:getline()
将读取流缓冲区中的任何内容,直到第一个n
。这意味着当您输入cin >> greeting;
时,如果您按enter, getline()
将读取n
之前尚未读取的所有内容,这是您的phrase
变量中的NOTHING,使其成为空字符串。一个简单的方法是调用getline()
两次。例如
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting; //IMPORTANT: THIS ASSUME THAT GREETING IS A SINGLE WORD (NO SPACES)
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
string rubbish_to_be_ignored;
getline(cin,rubbish_to_be_ignored); //this is going to read nothing
getline(cin, phrase); // read the actual name (first name and all)
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
假设您将该代码存储在文件stackoverflow.cpp中。示例运行:
Chip Chip@04:26:00:~ >>> g++ stackoverflow.cpp -o a.out
Chip Chip@04:26:33:~ >>> ./a.out
Exercise 3B
Kaitlin Stevers
String arrays
Please enter a greeting:
Hello
The greeting you entered was: Hello
Enter your full name
Kaitlin Stevers
Hello, how are you today Kaitlin Stevers?
在ubuntu 14.04上测试