How can I find and replace a line of data in a text file c++

后端 未结 2 857
死守一世寂寞
死守一世寂寞 2021-01-13 18:23

I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.

I was thinking of using replaceNumber.open(\"

2条回答
  •  自闭症患者
    2021-01-13 18:51

    You can use std::stringstream to convert the string read from the file to an integer and use std::ofstream with std::ofstream::trunc to overwrite the file.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
    
        std::ifstream ifs("test.txt");
        std::string line;
        int num, other_num;
        if(std::getline(ifs,line))
        {
                std::stringstream ss;
                ss << line;
                ss >> num;
        }
        else
        {
                std::cerr << "Error reading line from file" << std::endl;
                return 1;
        }
    
        std::cout << "Enter a number to subtract from " << num << std::endl;
        std::cin >> other_num;
    
        int diff = num-other_num;
        ifs.close();
    
        //std::ofstream::trunc tells the OS to overwrite the file
        std::ofstream ofs("test.txt",std::ofstream::trunc); 
    
        ofs << diff << std::endl;
        ofs.close();
    
        return 0;
    }
    

提交回复
热议问题