将用户输入到字符串中并将其写入文本文件-不工作

Taking users input into a string and writing it into a text file - Not working

本文关键字:文本 文件 工作 输入 用户 字符串      更新时间:2023-10-16

我的程序显示一条消息给用户输入,可以是没有长度限制的任何东西。

using namespace std;
void child() {
   string i;
   cout<<endl;
   cout<<"Enter your text:"<<endl;
   getline(cin, i);
   cout<<endl;
   ofstream out;
   out.open("pro1.txt");
   out<<i;
   sleep(2);
   out.close();
}
main()
{

int r = fork();
if (r == 0) // child
{   
    child();
    exit(0);
} else if (r < 0) // failed to fork
{
    cout << "Failed to fork" << endl;
    // Throw exception
} else // parent
{
  // Code only executed by parent process
  cout<<"im in parent";
}
    // Code executed by both parent and child.
}

这个输入将保存在一个字符串中,这个字符串将保存在文本文件中。我无法弄清楚我的代码有什么问题,因为它只需要第一个字母并将其保存在文本文件中。

请记住这是在子进程中应用的!

编辑:如您所见,我创建了一个新进程来完成这项工作

cin >> i;改为getline(cin, i);cin一旦发现空白,它将停止读取