Detect new line c++ fstream

后端 未结 3 771
花落未央
花落未央 2021-01-18 05:18

How do I read a .txt copy the content to another .txt by using fstream to a similar content. The problem is, when in the file there is new line. How do I detect that while u

3条回答
  •  被撕碎了的回忆
    2021-01-18 05:56

    If you want to remove text from the input file (as your description suggests but does not state).

    Then you need to read line by line. But then each line needs to be parsed word by word to make sure you can remove the work you are looking for apple.

    #include 
    #include  
    
    using namespace std;
    // Don't do this. 
    
    int main(int argc, char* argv[])
    {
        if (argv == 1) { std::cerr << "Usage: Need a word to remove\n";exit(1);}
        std::string userWord = argv[1];  // Get user input (from command line)
    
        std::ifstream inFile("note.txt");
        std::ofstream outFile("note_new.txt");
        std::string   line;
    
        while(std::getline(inFile, line))
        {
             // Got a line
             std::stringstream linestream(line);
             std::string  word;
    
             while(linestream >> word)
             {
                    // Got a word from the line.
                    if (word != userWord)
                    {
                         outFile << word;
                    }
             }
             // After you have processed each line.
             // Add a new line to the output.
             outFile << "\n";
        }
    }
    

提交回复
热议问题