将文本段落存储在变量C ++中

时间:2014-04-21 21:14:57

标签: c++

我正在尝试编写一个程序,它接受用户的输入并将整个段落存储在变量中。但是,如果用户输入:“你好,这是一些文字。”它只返回“你好”任何人都可以帮忙吗?

谢谢!

#include <iostream>
#include <iomanip>

using namespace std;

class GetText
{
public:

    string text;

    void userText()
    {
        cout << "Please type a message: ";
        cin >> text;
    }

    void to_string()
    {
        cout << "\n" << "User's Text: " << "\n" << text << endl;
    }
};

int main() {

    GetText test;
    test.userText();
    test.to_string();

    return 0;
}

2 个答案:

答案 0 :(得分:3)

您可以使用std::getline从用户输入中读取整行:

std::string text;
std::getline(std::cin, text);

Live demo

答案 1 :(得分:2)

使用cin获取值时,输入流默认将空格视为字符串拆分分隔符。相反,你应该使用std :: getline(),它读取输入直到它检测到新的行字符。

但是,正如我上面所说,std :: getline()读取输入,直到它检测到新的行字符,这意味着它一次只能读取一行。因此,为了读取包含多行的整个段落,您需要使用循环。

#include <iostream>
#include <iomanip>
#include <string> //For getline()

using namespace std;

// Creating class
class GetText
{
public:

    string text;
    string line; //Using this as a buffer

    void userText()
    {
        cout << "Please type a message: ";

        do
        {
            getline(cin, line);
            text += line;
        }
        while(line != "");
    }

    void to_string()
    {
        cout << "\n" << "User's Text: " << "\n" << text << endl;
    }
     };

     int main() {

    GetText test;
    test.userText();
    test.to_string();
    system("pause");
    return 0;
}

此代码逐行读取流,将当前行存储在字符串变量“line”中。我使用变量“line”作为输入流和变量“text”之间的缓冲区,我使用+ =运算符存储整个段落。它读取输入,直到当前行为空行。

相关问题