getline 不会从变量中读取字符串。 (C++)

发布于 2024-12-27 11:07:12 字数 542 浏览 1 评论 0原文

我试图让变量存储一个书面问题,然后将其写入文件,但是,getline 不会读取该字符串,当我尝试将其写入文件时,它只是不写入任何内容。

#include <iostream>
#include <fstream>
#include <string> 

using namespace std;

void addquestiontofile(){
    ofstream myfile;
    // Open file to be written to.
    myfile.open("quesitons.txt",ios::ate | ios::app);

    string newquestion;
    cout << "insert new question:  \n";
    getline(cin, newquestion); // This is the problem line

    if(myfile.is_open())
    {
        myfile << newquestion;
    }
}

I'm trying to make a variable store a written question which will then be written to a file however, the string is not being read by the getline and when I try to write it to the file it simply writes nothing.

#include <iostream>
#include <fstream>
#include <string> 

using namespace std;

void addquestiontofile(){
    ofstream myfile;
    // Open file to be written to.
    myfile.open("quesitons.txt",ios::ate | ios::app);

    string newquestion;
    cout << "insert new question:  \n";
    getline(cin, newquestion); // This is the problem line

    if(myfile.is_open())
    {
        myfile << newquestion;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风向决定发型 2025-01-03 11:07:12

从评论来看,听起来您已经使用了 cin >>>变量 从上一行输入中读取。这会将上一行的末尾留在输入流的缓冲区中,因此下一次调用 getline() 将产生一个空字符串。

您可以使用以下命令清除该行的其余部分

cin.ignore(numeric_limits<streamsize>::max(), '\n')

From the comments, it sounds like you have used cin >> variable to read from a previous line of input. This will leave the end of that previous line in the input stream's buffer, so the next call to getline() will yield an empty string.

You can clear the remainder of the line with

cin.ignore(numeric_limits<streamsize>::max(), '\n')
九歌凝 2025-01-03 11:07:12

之前的输入可能有一个尾随换行符。试试这个:

while (newquestion.empty())
{
    getline(cin, newquestion);
    boost::trim(newquestion);
}

There is probably a trailing newline from a previous input. Try this:

while (newquestion.empty())
{
    getline(cin, newquestion);
    boost::trim(newquestion);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文