字符串连接与C ++中的用户输入

问题描述 投票:-1回答:2

我尝试编写一个代码,该代码从用户获取输入并与另一个字符串连接,但它不能正常工作。代码低于,

#include<iostream>
using namespace std;
int main() {
    string s1="Hi ";
    string s2;
    cin>>s2;
    s1=s1+s2
    cout<<s1;
    return 0;
}

输入:

this is how it works

预期产出:

Hi this is how it works

但它并没有像我预期的那样奏效。输出是:

Hi this

有谁能够帮我?

string c++11 concatenation
2个回答
0
投票

'>>'读取以空格分隔的字符串。现在我发现getline用于读取线条。

#include<iostream>
using namespace std;
int main() {
    string s1="Hi ";
    string s2;
    getline(cin,s2);
    s1=s1+s2;
    cout<<s1;
    return 0;
}

现在我得到了所需的输出。


0
投票
#include <iostream>
using namespace std;

int main()
{
    string s1="hi ";
    string s2;

    cout << "Enter string s2: ";
    getline (cin,s2);


    s1 = s1 + s2;

    cout << "concating both "<< s1;

    return 0;
}

在这里使用这个!这应该有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.