2016-11-07 16 views
0

我正在绞拧一个简单的代码来学习更多关于字符串的知识。当我运行我的代码时,它不会显示我的姓氏。有人能解释为什么吗?我使用了字符串短语来存储它,它似乎只存储了我的名字。这是代码。字符串短语在空格处结束?

#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; 
} 
+0

它适用于我。你确定你没有看到所需的输出? – GMichael

+0

是的。也许我的编译器没有需要做字符串的文件。你会张贴你的出来的照片请。 –

+0

在我的编译器中,字符串甚至不会亮起另一种颜色。如果它工作正确,不是吗? –

回答

2

我使用的字符串短语来存储它,它只是似乎已经存储在我的第一个名字。

这很有道理。

cin >> phrase; 

将在输入中遇到空格字符时停止读取。

要阅读全名,您可以使用以下方法之一。

  1. 使用两个电话拨打cin >>

    std::string first_name; 
    std::string last_name; 
    cin >> first_name >> last_name; 
    
  2. 使用getline来读取整行。 getline将在一行中读取所有内容,包括空格字符。

    getline(cin, phrase); 
    
+0

谢谢。我想也许是这样! –

1

当您拨打cin >> phrase;时,它只会读取字符串,直到第一个非空格字符。如果你想在你的名字中包含空格,最好使用getline(cin,phrase);

重要提示:getline()将读取流缓冲区中的任何内容,直到第一个\n。这意味着当你输入cin >> greeting;时,如果你按下ENTER键,getline()会读取\n之前没有被读取的所有内容,这是你的phrase变量中没有的,使它成为一个空字符串。一个简单的方法是拨打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 [email protected]:26:00:~ >>> g++ stackoverflow.cpp -o a.out 
Chip [email protected]: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

+0

好的,谢谢你这么做! :) –