I'm writing simple console application in cpp but none of my approaches to write it were succesful. I'm trying to read row after row from ifstreamed file until the file ends.
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
void lowtempbin(string inpfile){
ifstream wyciag(inpfile.c_str());
string row_temp_bin;
int i=0;
while(getline(wyciag, row_temp_bin)){
i++;
cout<<i;
}
}
int main(){
lowtempbin("danesystemy.txt");
return 0;
}
Why the program doesn't enter while loop, and if getline does load nothing, then whole function should return 0? And then code after while is executed (not inside). I'll add that I pass as the argument to lowtempbin()inside main, name of the file that is in the same directory as executable (in code:blocks /project/bin/Debug). Also when I debug the application, while loop is never executed, as if getline returns negative value.
Code shoud cout all numbers, one for every row, but it just returns 0;
The program compiles and produces the expected result when ran.
Your problem seems to be one of the following:
The filename is incorrect.
The file is not in the same directory as the executable.
The file doesn't exist at all.
Related
I wrote this simple C++ program to compare two strings for a match. Although basic, it's very useful to me as I often need to verify details multiple times a day.
I want to initiate the program with a command name e.g. check4match (the program name) so I can run the program in the terminal.
#include <iostream>
#include <string>
using namespace std;
void match(string, string);
int main() {
string addrOne, addrTwo;
cout<<"Insert str one: "; cin>>addrOne;
cout<<"Insert str two: "; cin>>addrTwo;
match(addrOne, addrTwo);
return 0;
}
void match(string addrOne, string addrTwo){
if(addrOne == addrTwo)
cout<<"SAFE: strings match";
else
cout<<"WARNING: N0 match found";
}
Ok, as always relatively simple in the end. So chmod a+x didn't work to make the cpp program executable. Simple make filename (without the .cpp extension).
Then I moved the newly made .exe file to /usr/local/bin. I had to drag & drop the file, as moving via terminal command wasn't allowed, even with sudo.
I wrote a code to make "text1.txt" file. It worked correctly, then I've been trying to read from the file, but every time is_open() function doesn't return true. Even so I copied other codes in the way exactly they are in different compilers, but it never works. How will I solve this:(
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file1("text1.txt");
string str;
if(file1.is_open()){
while(getline( file1, str)){
cout<<str;
}
}
else
cout<<"the file is not open"<<endl;
return 0;
}
How are you running your program?
The most common cause of this I've seen is that you're running your program inside an IDE (like Visual Studio), and your current directory isn't where you think it is.
Try putting in the full path to the file and see if your problem disappears.
I have the task to write a function that reads a line from a text file (renamed to .dat, however it contains only text), but I am out of options for a solution because of the following points:
I am using Borland C++ Version 5.02, and no, I CANĀ“T download another compiler because I dont have admin rights on my laptop and the guy who has the needed password isnt there until next week.
The compiler does not accept using namespace std, and also it doesnt accept getline(), no matter if string and iostream are included or not.
I am trying to find a solution or at least the tiniest approach, but I am unable to find one.
So my question is: How do I read a line from a simple textfile without using getline() (cin.getline works, the ones from string or fstream doesnt) ? The textfile contains several lines like these:
1234;12.05.03;08:44:23; XY12-AB;A1-12;Timeout
2345;12.05.03;09:04:34;XY1-CD;A22-9;Connection refused
And the numbers/letters between the ; need to be stored in variables so they can be worked with.
Im not asking for you to write my code, but I am reallyreaylly frustrated and my instructor is no help.
Live long and prosper,
Me.
http://www.cplusplus.com/reference/string/string/getline/
If you cant use (which you really shouldnt)
using namespace std
Then refer to your namespace with :: operator
For example:
std::string
Now try to write your own code using std:: and comment if you still cant do it.
Also, there is a lot of other options than std::getline() to read line of text.
Ref: Read file line by line
Option 1:
Try using the C's fgets() function.
Option 2:
You mention that cin.getline() works. You can freopen stdin with the input file and then cin will point to mentioned file. After that cin.getline() will read from the file:
Downside: After the freopen you will not be able to accept any input from the user.
Example: Note this has not been tried using g++ but I guess it should work with Borland too.
#include <iostream>
#include <stdio.h>
int main() {
char buf[1000];
freopen("somefile.dat", "r", stdin);
while (cin.getline(buf, sizeof(buf)).good()) {
// Now buf contains a line
// Do something with it
}
return 0;
}
Try using
getline(cin >> ws, variableName);
But first, you have to use
using namespace std;
I'm having the same problem while i using multi dimensional array on structs into a file, i have try different ways. But then i tried this one and it's work for me.
So in my case it gonna be like this
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myFile;
myFile.open("test.txt");
int count = 0;
while (!myFile.eof())
{
getline(myFile >> ws, data[count].string1);
getline(myFile >> ws, data[count].string2);
myFile >> data[count].int1;
for (int i = 0; i < data[count].int1; i++) {
getline(myFile >> ws, data[count].data2[i].string3);
}
count++;
}
return 0;
}
For more : https://www.geeksforgeeks.org/problem-with-getline-after-cin/
I have a program that reads in a file. All my classes compile fine, but there seems to be an error when I read in the file. Eclipse shows an empty string is being read in (""), which is not what I want.
I have the code for my main below with a while loop. I placed the loop just to see how it would run when debugging, and it runs an infinite loop since it is always reading in "", and never reaches end of file. I have put the file in the working directory and every other folder just to be sure, but it is always doing this even though the file is full of strings and integers. Is there anything I am doing wrong here?
#include "Translator.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
ifstream readFile;
readFile.open("sample.html");
while (!readFile.eof()) // for debugging purposes only
{
string x;
readFile >> x; // x is "" everytime through the loop
readFile >> x; // x is also ""
}
Translator t(readFile);
readFile.close();
return 0;
}
My guess is that your file did not actually open, and the eof bit was therefore not set. You never test whether the file was opened successfully. It could be that your working directory is not what you think it is, or the file is locked by another process (perhaps open in a text editor).
Officially, you can test readFile.fail() after you try opening.
I've found that checking readFile.good() is fine too - in fact you can use that as your loop condition.
I prefer the positive message of 'good' in my code, rather than the potentially upsetting 'fail'.
You should also test your stream as WhozCraig suggested in comments, when you are reading data. You cannot assume that the operation was successful. If it fails for reasons other than EOF, you need to know.
For these reasons, don't use readFile.eof() as your loop condition.
I am just learning the very basic aspects of input/output streams, and can't seem to have my program read a text file. It gives me errors that indicate it is trying to read the .txt file as C++ code, while I am just using values in there to test my stream.
These are the contents of my included .txt file:
12345
Success
And here is the main program's code:
#include <fstream>
#include <iostream>
#include "C:\Users\Pavel\Desktop\strings.txt"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
ifstream in;
in.open("C:\Users\Pavel\Desktop\strings.txt");
int x;
string sz;
in << x << sz;
in.close();
return 0;
}
The first error message I receive is "expected unqualified-id before numeric constant" which tells me the program is attempting to compile the included file. How can I prevent this and have the text file read as intended?
Don't #include your .txt file. Includes are for source code. They textually insert the file into your code, as if you had actually copy-pasted it there. You shouldn't be #includeing a file you're opening with an ifstream.
Opening files on the filesystem at runtime doesn't require any mention of that file's name in the source code. (You could, for instance, ask the user for a filename, and then open it just fine!)
The case where you might #include data in your source would be if you wanted to have that data embedded into the executable of your program (and thus not rely on a file that was on the filesystem when running). But to do that, you have to format your file as a valid C++ data declaration. So it would not be a .txt file at that point.
For instance, in strings.cpp
#include <string>
// See http://stackoverflow.com/questions/1135841/c-multiline-string-literal
std::string myData =
"12345\n"
"Success";
Then in your main program:
#include <iostream>
#include <sstream>
#include "strings.cpp"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
istringstream in (myData);
int x;
// Note: "sz" is shorthand for "string terminated by zero"
// C++ std::strings are *not* null terminated, and can actually
// legally have embedded nulls. Unfortunately, C++ does
// have to deal with both kinds of strings (such as with the
// zero-terminated array of char*s passed as pszArgs...)
string str;
// Note: >> is the "extractor"
in >> x >> str;
// Note: << is the "inserter"
cout << x << "\n" << str << "\n";
return 0;
}
Generally speaking, just #include-ing a source file like this is not the way you want to do things. You'll quickly run into trouble if you do that in more than one file in your project (duplicate declarations of myData). So the usual trick is to separate things into header files and implementation files...including the headers as many times as you want, but only putting one copy of the implementation into your build process.
An #include directive works the same way regardless of the extension of the file being included - txt, h, no extension at all - it doesn't matter. How it works is the contents of the file are pasted into your source file by the preprocessor before that file is passed to the compiler. As far as the compiler is concerned, you might as well have just copied and pasted the contents yourself.