C++ Text Files usage [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am currently learning how to use text files, but when i put a condition like the one in the code below, even if the condition is true it won't try the while part. Can anyone help out?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string s, d;
ofstream k("t1.txt");
int a;
cin >> a;
if (a > 3)
{
while (k.is_open())
{
getline(cin, s);
k << s;
k.close();
}
}
ifstream r("t1.txt");
while (r.is_open())
{
getline(r, d);
cout << d;
r.close();
}
}

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.

Related

GDB Skips While Loop Condition When Used With File Input

Alright Stack Overflow, I am running into a decently persistent problem in my C++ code. I'm sure this is one of those dumb mistake moments, but I have tried everything and cannot seem to squish this bug.
I have a bit of code here, and it's behavior is very odd. I have a main function that opens a file containing text I want to read in. I was taught in programming fundamentals class at my university that I could use getline() as a condition for the while loop, which is nice since it automatically terminates when it reaches the end of the file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream input_mem_traces("gcc.txt");
string trace_to_parse = "";
while(getline(input_mem_traces, trace_to_parse))
{
cout << trace_to_parse << endl;
}
}
When I compile and run it, it works just fine. It reads out every single line of the file I pass it, and returns with no problems.
However, when I try to use gdb, and set a breakpoint at the line
cout << trace_to_parse << endl;
it didn't hit the breakpoint. Curious as to why that was, I broke above the loop, and tried single stepping through the code. When I got to the while loop, and tried to step, it simply skipped to the line after it, which happened to be the end of the program.
This behavior occurs both using the VSCode GUI front end for gdb, as well as straight gdb from the command line. I am running this on Windows using Ubuntu under WSL2, and VSCode as my IDE with the Remote - WSL extension enabled.
Turns out there was some weirdness going on with the working directory with GDB. For some reason, my working directory was changing under the VSCode GUI, thus the file was not able to be opened, and the while loop condition performed as expected for that circumstance by not entering the loop. Upon the recommendation by Retired Ninja in the comments, I used an absolute path in the fstream object constructor, and that solved the issue.

White space on the end of output string not printing with the string, but rather with the next printed line after it

I tried to print a line that asks for input from the user, get the input, then print again some line. The problem is that the white space at the end of the first printed line is printed not at the end of the line, but rather at the beginning of second printed line, after i get the input.
I'm completely new to C++ so I couldn't really try much, but i tried printing the code without the part that prompts the input from the user, and it prints the space just fine, but when i add std::cin << input; the space get's sent to the beginning of the second line.
My code:
int input;
std::cout << "Enter your favorite number between 1 and 100: ";
std::cin >> input;
std::cout << "Amazing... That's my favorite number too... wow..." << std::endl;
I want the output to be
Enter your favorite number between 1 and 100: //some input
Amazing... That's my favorite number too... wow...
(note the space before //some input)
Instead i get
Enter your favorite number between 1 and 100://some input
Amazing... That's my favorite number too... wow...
(note the space before Amazing)
Edit: I'm using Clion if it could be connected. Also, I tried to run the executable on powershell and it worked as expected, without the problem, so this has something to do with the Clion terminal. Also, i'm using windows 10 as my OS.
Second Edit: add my findings on my answer.
This seems to be a problem with buffered input of Clion. See this issue: https://youtrack.jetbrains.com/issue/CPP-7437
When you are using CLion, You can try disabling PTY (Help | Find Action > type "Registry" > open Registry > find and disable the run.processes.with.pty option)
CLion moving space into new line
Are you sure about that? I tried both in online shell and on local machine and it works as expected.
After checking I found out that this occurs only on the Clion Run terminal, so this has something to do with it exclusively. I'm currently trying to mess around with the settings. I will post a solution and an explanation here if I find it.
Edit: as mentioned in one comment, it could be the issue mentioned here https://youtrack.jetbrains.com/issue/CPP-7437.
In any case it is a Clion related problem exclusively, and not a C++ problem.
This problem is only applicable for the second line, if you leave that line empty then the problem will be fixed. Don't know about C++ but for C before the print statement you have to add: printf("\n");

In Xcode 8.3 update, C/C++ programming printf does not give output without newline

After last week's updated to Xcode 8.3, in a C/C++ program the output from a printf statement no longer appears on the screen without a newline. Thus I can't prompt for the user to enter a number, and have them type in that number on the same line following the input prompt.
Neither flushing the output buffer [fflush(stdout) or cout << endl] nor setting the output buffer to NULL [setbuf(stdout, NULL)] addresses this problem, but rather is a question specifically about Xcode 8.3 seemingly being broken.
With the scanf commented out, the output of the program below is:
Enter a value for x: Value of x is: 0
With the scanf in place, the output from the first printf never shows up. If you go ahead and type in a value and press enter, only then does it show up. Output is:
3
Enter a value for x: Value of x is: 3
Full test program is here:
#include <iostream>
using namespace std;
int main() {
int x=0;
printf("Enter a value for x: ");
//scanf("%d", &x);
printf("Value of x is: %d\n", x);
return 0;
}
My work-around has been to revert back to Xcode 8.2.1, downloaded from developer.apple.com/xcode/downloads/
8.3.2 was announced last night and addresses this supposedly:
It is standard behavior in C for stdout to be flushed when an input function is called, such as scanf(), regardless of whether a newline was output prior to the call or not. This ensures that all appropriate output is displayed before the input operation takes place. Therefore, the update might have broken something in Xcode. Although I'm not currently sure what the exact nature of the problem is, a (temporary) workaround is to run your application on the command line. This has worked for my projects. It also reveals that this problem is with the Xcode output window, and not the compiler or something else.
In response to tell's comment: no, flushing stdout does not correct the issue within Xcode. This implies even more strongly to me that the issue is definitely in the Xcode interface itself. When running the application from the command line, calls to fflush() work as expected.
Also, printing to stderr makes no difference from within Xcode. Basically, stdout should be flushed in this case without appealing to stderr or any other gimmicks because the OP is calling scanf(). It works perfectly from the command line... just not in the Xcode output window.
And please note this this question is not a duplicate: it has nothing to do with anyone's misunderstanding of how C input and output work, and everything to do with the fact that a recent update to Xcode broke something.
EDIT:
Thanks, joe_04_04. The update certainly seems to have fixed the problem.

C++ output screen disappears

Why does my C++ output screen disappear immediately? I'm a beginner in cpp. Can anyone help me to find the problem please?
You should either launch your application inside of a terminal, or add a line of code that waits for the input in order for the window to not close. E.g. add in the end of the function main a line:
std::cin.get();
And also add at beginning of the file the include that holds that function.
#include <iostream>
This is hard to answer since there can be many things that can cause your output box to close immediately. First try having a cout statement and then a cin statement. Something like:
cout<<"Hello"<<endl;
cin>>input>>endl;
Also make sure to have the necessary include statement at the top and whatever you want to return at the bottom.
#include<iostream>
return 0;
As you have said that you are beginner in C++, you should keep in mind ,three major things while coding in C++. You've mentioned that your screen disappears , then following things you should try.
1). in C++ conventionally main returns value of type int.And the format of your program should be like...
int main()
{
-------
//body of your program
-------
return 0;
}
If the function returns 0, that means it ran successfully.
2). You have to inlcude #include<iostream> on the top of your program.
3).check whether the IDE you are using is compatibale to your operating system or not.
Hope this will help you.

"No newline at end of file" warning, even after putting in a newline [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've been trying to learn C++ lately, and all has been going well until today. I'm trying to make a very simple application that basically just asks a user for a number and then displays the factorial of that number.
When I try to compile the file in Cygwin (g++ factorial.cpp -o fact), I get the following warning "warning: no newline at end of file". Following the words of the warning, I added a newline at the end of the file and tried it again...with the exact same result. Whether I try one newline or twenty, it never seems to compile.
I attached the simple, and still unfinished, file below (Except imagine there is a blank line at the end of it. This noob can't get it show up in code view):
#include <iostream>
#include <string>
using namespace std;
int getInput();
void displayFactorial(int);
int main()
{
int number = getInput();
displayFactorial(number);
return 0;
}
int getInput()
{
int userNumber;
bool okNumber;
while(okNumber == false){
cout << "Please eneter a number in the range of 1-10";
cin >> userNumber;
if(userNumber >= 1 and userNumber <=10){
okNumber = true;
}
else{
cout << "Incorrect number" << endl;
}
}
return userNumber;
}
void displayFactorial(int number){
string displayString = number + "! =";
int total;
for(int i = 0; i<=number; i++){
//displayString += "
}
cout << displayString;
}
// File ended the line above this (with a new line. This line added by Martin so it shows)
Any idea what could cause that warning if it's not the newline?
First of all a warning does not prevent a program from compiling.
Second: Are you sure you compile the file you are editing?
I held some tutorials at my university and most of the beginners made this mistake.
If you can definitely say you are compiling the file you are editing, then it could be caused by different new line settings but I consider this highly improbable.
Which editor/IDE do you use?
All you have to do is wait for the new C++0x standard. A newline is no longer required at the end of the source file. (And this took 40 years?)
Most Unix-based text editors will add a trailing newline automatically, but apparently
Notepad++ (which I've never used) doesn't.
The file doesn't need to end with a blank line (which would be represented as two newline
characters in a row), just a properly terminated one.
See if Notepad++ has a configuration option that tells it to automatically append a newline
when saving a file, or at least to ask whether you want to add one.
Great explanation - I had the same problem and solved it simply by using WordPad instead of Notepad :)
The problem has nothing to do with your C++ code; I can almost guarantee you that the uninitialized boolean in your program didn't cause the issue. It's a problem with the source file itself. A "Hello, world" program would have produced the same warning.
A text file, including a C++ source file, consists of lines of characters, where each line is terminated by an end-of-line marker. In Unix, and therefore in Cygwin (with the default settings), the end-of-line marker is a single '\n' (newline, linefeed) character. (Windows uses CR-LF pair ("\r\n").
It's possible for the very last line of a text file not to end with a newline character, but g++ prefers it to be terminated properly.
Most Unix-based text editors will add a trailing newline automatically, but apparently Notepad++ (which I've never used) doesn't.
The file doesn't need to end with a blank line (which would be represented as two newline characters in a row), just a properly terminated one.
See if Notepad++ has a configuration option that tells it to automatically append a newline when saving a file, or at least to ask whether you want to add one.
(The missing newline at the end of the file is probably what caused your problems pasting the code when you posted the question.)
Maybe it is some problem with some invisible character? I copy-paste your code and gets compiled without any warnings/errors, under Cygwin with the following g++:
$ g++ --version
g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
It ended up that not initializing a boolean variable to false was the issue. However, I'm not sure whether it was actually the initialization that was the problem, or just the fact that the text editor might not actually save a file if you just append whitespace to the end of it. For those wondering, this was happening to me in Notepad++.