I wrote the code below that successfully gets a random line from a file; however, I need to be able to modify one of the lines, so I need to be able to get the line character by character.
How can I change my code to do this?
I wrote the code below that successfully gets a random line from a file;
Share
Use
std::istream::getinstead ofstd::getline. Just read your string character by character until you reach\n, EOF or other errors. I also recommend you read the fullstd::istreamreference.Good luck with your homework!
UPDATE:
OK, I don’t think an example will hurt. Here is how I’d do it if I were you:
… the only thing is that I have no idea why do you need to read string char by char in order to modify it. You can modify std::string object, which is even easier. Let’s say you want to replace “I think” with “what if”? You might be better off reading more about
std::stringand usingfind,erase,replaceetc.UPDATE 2:
What happens with your latest code is simply this – you open a file, then you get its content character by character until you reach newline (
\n). So in either case you will end up reading the first line and then your do-while loop will terminate. If you look into my example, I did while loop that reads line until\ninside a for loop. So that is basically what you should do – repeat your do-while loop for as many times as many lines you want/can get from that file. For example, something like this will read you two lines: