简体   繁体   中英

Save user input to a text file c++

I've been writing a program that simulates the terminal on your computer. One of the options is to write some text and save it into an existing text file, however I've been having trouble saving the whole input into the file.

Here's what triggers the write-to-file:

else if(command == "write"){
   ofstream myfile (arg.c_str());
   string writeToFile;
   std::cout << "Opening file '"<< arg.c_str() << "'...\n" << std::endl;
   std::cout << "Plese enter what you want to write into the file:\n" << std::end;

   std::getline(std::cin, writeToFile);

   if (myfile.is_open()){
     myfile << writeToFile << "\n";
     myfile.close();
   }

   std::cout << "You wrote: " << writeToFile << std::endl;
   std::cout << "File succesfully updated. \n" << std::endl;
   commandStart();
 }

However when I use the std::getline(std::cin, writeToFile); this is the result: 使用 std::getline(std::cin, writeToFile);

It doesn't let me type anything to save to the file and it automatically closes, however, when I use this:

else if(command == "write"){
   ofstream myfile (arg.c_str());
   string writeToFile;
   std::cout << "Opening file '"<< arg.c_str() << "'...\n" << std::endl;
   std::cout << "Plese enter what you want to write into the file:\n" << std::end;

   std::cin >> writeToFile;

   if (myfile.is_open()){
     myfile << writeToFile << "\n";
     myfile.close();
   }

   std::cout << "You wrote: " << writeToFile << std::endl;
   std::cout << "File succesfully updated. \n" << std::endl;
   commandStart();
 }

using the std::cin >> writeToFile; I'm allowed to type something and save it into the file, but it only saves the very first word:

使用 std::cin >> writeToFile;

Any ideas of why this is happening? I've already checked other questions and sites but I haven't been able to solve this issue.

basically the cout '\\n' is read by your getline function. std::cin.ignore() after the cout() will solve your issue.

as mentioned by MikeCAT Why does std::getline() skip input after a formatted extraction? answers go in depth to explain the reason, definitely worth a read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM