[Solved] C++ Text Files usage [closed]


I ran the code in gdb, it runs perfectly. It opens the file, gets the < cr > character from stdin, writes that to the first line which wipes out the first line, then tries to read the first line which is empty so there is no output. Good job 8).

You’re just having trouble understanding your own expectations, your code works fine, so just think a little bit more about what you think it’s supposed to do.

You’ll also need to examine the contents of your text file before and after running the code, and try entering some text in the text file before you start the program, to see what happens to the text.

The getline where you try to read from the console is the issue, that returns without asking for input so it ends up giving you a blank line to write to the file.

From this link:
http://www.cplusplus.com/forum/beginner/39549/

There’s a similar question there, and the first of the comments mentions this about the behavior of getline:
std::cin leaves the newline character in the buffer after pressing enter, and getline just grabs it and keeps going, that’s why getline doesn’t block to wait for input. …….

That’s why it’s not “doing anything” – it’s not asking you for input, so the program has nothing to output and it looks like it’s not working.

(this, by the way, is why programmers are snarky – we have to deal with stupid little behavioral issues of machines and we forget that PEOPLE are not normally like this and that PEOPLE hate being held to these kinds of standards)

I put a second getline in your code right after hte first one and now it asks for and outputs a string that I type in and sticks it in the file.

To run the program in gdb, do the following:

g++ -g < your cpp file > -o < whatever you want the binary to be called >

like this:
g++ -g myfile.cpp -o myrunnableprogram

this creates a binary with symbols that you can open in gdb

then

gdb myrunnableprogram

then in gdb

start

next

next

next

….

these commands will start the program and pause it at the first breakable spot, then each time you type next you will step to the next command and you can poke around at variables to see what’s going on.

read up on gdb, it’s really useful.

3

solved C++ Text Files usage [closed]