当通过不同的方法给出输入时,为什么同一程序会给出不同的输出?

程序1:

int main(){
    char s[10];
    cout << "Enter a String\n";
    cin >> s;
    cout << "The entered String is\n";
    cout << s << "\n";
    return 0;
}

当我通过命令行“Hello World”提供输入时,我得到的输出仅为“Hello”

程式2:
int main(){
    char s[] = "Hello World";
    cout << "The entered String is\n";
    cout << s << "\n";
    return 0;
}

在这种情况下,我将获得“Hello World”的输出。

这两个程序有什么区别?逻辑是一样的吗?通过命令行输入时,如何获取整个字符串“Hello World”?有办法吗?

最佳答案

使用 getline() :

string s;
getline(cin, s);
cout << "The entered String is\n";
cout << s << "\n";

您的代码的问题在于,输入流提取运算符>>仅使字符到达下一个空格(因此,只有一个“单词”)。 getline()函数获取整行。

08-18 13:39
查看更多