Trouble with getline when using eclipse's console - c++

I recently started to use eclipse for my C++ code, and wanted to run a simple function that asks the user for a filename, then reads from the file and sums up all the numbers to test it out.
string filename;
do {
cout << "Enter File Name: "; // Asks for user input
getline(cin, filename);
}
while (filename.empty());
ifstream myfile (filename);
if (myfile.is_open()) {
// sums up text file & outputs it
}
else {
cout << "Error Opening " << filename << endl;
}
The program works perfectly when I run it via Windows Command Prompt in my executable folder and type in the filename. However, when I try to run it via eclipse's console using the exact same input, where I've set the working directory to the project root where the file most definitely exists, the file does not open.
If I change a single line:
ifstream myfile("test1.txt");
Then the code works again perfectly. So now I've narrowed down that for some reason, the Eclipse console interprets my text input via getline differently from the windows command prompt, but I'm not sure what I can do so it behaves consistently.
Calling
cin.ignore()
Before calling getline() just removes the first character of my input (so it tries to "est1.txt") instead.
Any idea what exactly eclipse does to its console that makes getline unreliable? And if this is the case, what I should do to work around it?

Related

Unable to write to file output.txt

I'm trying to write a program. The first file will be opened for input and the second file will be opened for output. (It will be assumed that the first file contains sentences that end with a period.) The program will read the contents of the first file and change all the letters to lowercase except the first letter of each sentence, which should be made uppercase. The revised contents should be stored in the second file.
I've been able to get my code to work in that I successfully converted the contents in input.txt to the above requirements (all sentences are lowercase except for the first word in each sentence). However, this content does not appear in output.txt
Both input.txt and output.txt are in the same directory next to main.cpp.
I tried using different IDEs but that didn't do anything. I also tried moving around the location of output.txt but that did nothing also.
SAMPLE INPUT: google's homepage includes a button labeled "I'm Feeling
Lucky". When a user types in a search AND clicks on the button the
user will be taken directly to the first search result, bypassing the
search engine results page.
SAMPLE OUTPUT: Google's homepage includes a button labeled "i'm
feeling lucky". When a user types in a search and clicks on the
button the user will be taken directly to the first search result,
bypassing the search engine results page.
string inFileName, outFileName;
string line;
char c;
cout << "Enter input file name: ";
cin >> inFileName;
fstream fin, fout;
fin.open(inFileName.c_str(), ios::in);
fout.open(outFileName.c_str(), ios::out);
if (fin.fail())
{
cout << "INPUT FILE DOES NOT EXIST (DNE)\n";
system("pause");
return 1;
}
Nothing shows up in output.txt (it's blank). From what I've noticed this command fout << line << "." << endl; isn't doing anything.
[Here's another screenshot]that shows what's in my terminal as well as what is in input.txt and output.txt:
You'll notice that in the terminal the proper conversion is shown but I am unable to get that text in the terminal into output.txt.
After every source code is compiled, a executable program is created. On Windows, it has .exe extension. The program should have the same name from your source code.
Try to find where it is created. It can be inside the temp folder or maybe where Visual Studio is installed.
Your text document (.txt) file for storing output has to be in the same directory with the executable.
I executed your program on my device (on Code::Blocks IDE though). It went as it should.
I agree with all the above answers and they are appropriate for all the users. In my case though there was a segmentation fault that led to file write failure. Try rectifying any segmentation faults.

C++: getline freezes at end of file

I want to read in one file line-by-line and output each line I read to a new file. In this code, cin has been redirected to refer to the input file, and cout has been redirected to refer to the output file.
The loop successfully writes every line in the file, but then it gets stuck on the final getline call. As a result, "Done" is not written to the file and the program does not terminate.
#include <string>
#include <iostream>
using namespace std;
int main() {
string line;
while(getline(cin, line)) {
cout << line << endl;
}
cout << "Done";
return 0;
}
Strangely, if I forcibly terminate the program, it seems to suddenly execute as desired, with "Done" being written.
Can someone point me in the right direction? Is there a flaw in the code, or is this some external configuration issue?
Notes: The input file in question ends with a newline character. Also, I do not want to use any includes besides these two.
The code should terminate on end of file (EOF) or any sort of file error. (The getline being called is:
http://en.cppreference.com/w/cpp/string/basic_string/getline
It returns the cin istream and then invokes its boolean conversion operator:
http://www.cplusplus.com/reference/ios/ios/operator_bool/
that checks if badbit or failbit is set on the stream. The failbit state should be set when a read is attempted with the stream already at EOF, or if there is an error.)
Per the comments above, it seems like this does work when the code is run from the shell directly. My guess is Eclipse is doing something complicated where it either intentionally sends the file into the program and then switches to an interactive input mode, or has a bug in which it doesn't close its end of a pipe or pty/tty it is using to send input to the program. (I.e. Eclipse is not binding stdin directly to the file itself in running the program.)
If one wanted to debug it further, one could look at the process state using tools like lsof. (Assuming a UNIXy system.) Might also be worth raising the issue in an Eclipse forum. The IDE is not my area of expertise.

Qt reading from console and stop when Enter has pressed

QTextStream cin(stdin);
QTextStream cout(stdout);
QString path;
cout << "Set directory to save configuration file: ";
cout.flush();
// path = cin.readLine();
cin >> path;
Here is the code. It works fine when you need to enter some text into console. It prints message and then waits until you write some text and then press the Enter key. BUT, if you don't want to enter any text and you want to leave path string empty, this code doesn't approach: it doesn't recognize Enter as end of the line/new line, so if you try to press Enter without writing any text, cursor would be only switched to the next line and program would still wait until you'll write something.
So, is there any way to recognize Enter key NO MATTER if path string empty or not? Simple: you press Enter key - program stops to read from console.
For QT you could use QTextStream::readLine.
Instead you could also use std::getline along with the normal std::cin and std::cout.
The only way i found is to go to the project tab on Qt Creator, got to run, and check run "in terminal" (under "working directory"). This will just run in external terminal which does recognize the enter key.

Having trouble with fstream in Xcode

I'm having trouble validating the existence of REGISTER.txt for input purposes in a function (see below). My understanding is that if the file doesn't exist, then the file won't be opened and the file stream variable (inData) will be false. Thus, I can use that variable in an if/else statement to verify whether or not it opened. But even though REGISTER.txt is in the same directory as my .cpp file, my code still says that it wasn't opened.
Here's the thing though. When I run the same exact code in Dev-C++ compiler, it works fine and the file is found. Now, I understand compilers are different, but I don't understand what is causing the discrepancy here. My preferred IDE is Xcode, so I'd like to learn how to do I/O with files in Xcode.
Thanks in advance for the help.
P.S. My Xcode project references the file, so it's not like the project isn't connected with the file.
void ReadVehicleRegInfo(char& vehicleType, string& licensePlate,
int& modelYear, float& origTaxValue, bool& error)
{
ifstream inData;
string inputFile = "REGISTER.txt";
inData.open(inputFile.c_str()); //File contains registration info
if (!inData) {
//File does not exist. Exit function
cout << inputFile << " does not exist. Program will now terminate"
<< endl << endl;
error = true;
return;
} else {
//File exists - continue with program
cout << inputFile << " found";
}
inData.close();
}
In my main() function, I have the following code to signal to the user that an error has occurred:
if (error) {
//Function encountered error. Exits program
system("PAUSE");
return 99;
}
EDIT
I spent 40 minutes trying to figure this out, 15 writing the question, and 5 minutes after I post it I make huge progress. Don't you love that?
I put in the full directory to the file and that did the trick.
However, this is not ideal. The next question is how do I avoid having to do that? What is the default directory for Xcode?
Normally it would be the directory where your program lives. If you want to make sure, use _getcwd to get the current directory or just include the parent directory.
char *_getcwd(
char *buffer,
int maxlen
);
However, you should try not to use the full path for the reason it might not be the same when you run your program on another computer.
REGISTER.txt is in the same directory as my .cpp file
REGISTER.txt needs to be in the same directory as the binary (build/Release or elsewhere depending on your build settings)

how to make input prompt for 7 column by ifstream

I typed in a file name which I want to show on prompt screen but it says that
"'c:\test\sp.csv' is not recognized as an internal or external command,"
even though the file is available on the path.
1 - Why did this error happen? How to fix it?
C:\Users\MS>c:\test\sp.csv
'c:\test\sp.csv' is not recognized as an internal or external command,
operable program or batch file.
2 - The code below only shows one column, if I want to input for 7 columns, how would I edit the code below?
How to print out on prompt screen using ifstream for 7 column with header and price.
Date Open High Low Close Volume Adj Close
6/21/2013 1588.62 1599.19 1577.7 1592.43 5797280000 1592.43
6/20/2013 1624.62 1624.62 1584.32 1588.19 4858850000 1588.19
int main(){
int open;
string fileName;
cout <<"Enter a file name: ";
getline(cin, fileName); //c:\\test\\sp.csv
ifstream inFile(fileName.c_str(), ios::in);
while(!inFile.eof()){
inFile >> open;
cout << open << endl;
}
inFile.close();
system("PAUSE");
return 0;
}
Thank you Kelly
Looks like you're on Windows OS
.csv file extension is not an executable one. It won't get "executed", even if its present in current working directory/folder.
Probably what you want is a .exe, .com or .bat file.
Here, in this case I think you want your .CPP 's executable with command line argument.
May be something like
C:\Users\MS>c:\test\sp.exe c:\test\sp.csv' Considering your C++ file name is sp.cpp
2 . Looks like you want to display out all contents of sp.scv
You may want to read the header first (i.e the Titles), and then read the values.
There are lot of question already asked on StackOverflow, related to this, please refer them.
Also for proper formatting you may want to use std::setw