Can't read from file all integers of a line (ifstream) [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This function is supposed to open a .txt file like this:
1 4 5
2 4 6
etc. (with tab between numbers)
and save each number in one variable
void Graph::readData(char* fname)
{
//cout<<"1";
int x,y,w;//assistant variables
ifstream input;//stream for reading file
input.open(fname,ios::in);
if(!input)
{
cerr<<"Input file doesn't exist"<<endl;//error if file doens exist
}
else
{
cout<<"Input file opened"<<endl;
cout<<"Reading Data from file..."<<endl;
while(!input.eof())//till the end of file
{
input>>x>>y>>w;//reads the links-site
cout<<"x: "<<x<<"y:"<<y<<"w: "<<w<<endl;
insertLink(x,y,w);//inserts them
}
input.close();//closing file
}
}
However, when I "cout" the results I get something like this:
x=1 y= w=5
x=2 y= w=6
without y!
Why could this happen?
PS: In addition, eof() becomes true after the file is finished (reads one extra line). How can I stop while iteration properly?
This is the file I'm trying to read from: http://www.speedyshare.com/tpvuD/input.txt

To stop the iteration properly, write the loop as:
while(input>>x>>y>>w)//till the end of file
{ /* ... */ }
Do not check input.eof().

Related

Reading from 3 column txt file to different arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to read a three column and N row txt file to three different arrays:
int N=100;
double x[N],
y[N],
z[N];
ifstream reading;
reading.open("reading.txt");
reading.close();
What should I write in the empty region? x[j], y[j], z[j] should be element in j'th row and first, second and third column respectively.
Once you get the input file stream, it will be similar to reading from a standard input.
As a hint I can say, what about reading every integer and then store them appropriately. For example,
1 2 3
4 5 6
7 8 9
Now you read everything like this
while (redaing>> num) {
// here you would know whether you are reading the first number
// or second number or third.
// x[xi] = num or y[yi]=num or z[zi]=num
}
Also you need to do something before you start reading from a file using the input file stream.
Have this check to make the program more safe.
if (!reading) {
cerr << "Unable to open file reading.txt";
exit(1); // call system to stop
}
A solution would be like this:
int xi=0,yi=0,zi=0,iter=0;
while(redaing >>num){
if(iter%3==0)x[xi++]=num;
else if(iter%3 ==1)y[yi++]=num;
else
z[zi++]=num;
iter++;
}
More succintly as pointed by user4581301
while(redaing >>x[xi++]>>y[yi++]>>z[zi++]){
//..do some work if you need to.
}
Also another from comment to limit the 100 line reading is [From comment of user4581301]
int index = 0;
while(index < 100 && redaing >>x[index]>>y[index]>>z[index] ){
index++;
}
A better solution:
vector<int> x,y,z;
int a,b,c;
while(reading>>a>>b>>c){
x.push_back(a);
y.push_back(b);
z.push_back(c);
//..do some work if you need to.
}
I'm kind of confused on the wording of your question could you try and reword It? Also if you want to read to the nth row I would use a while loop with the condition being while not end of file. Also you may consider using a vector since you don't know how large of an array you want to create.
A trivial way is
Read the file line by line using getline().
Get the line into an istringstream.
Use istringstream as any istream like cin, it will only contain one line of text.
I would suggest you to search for these terms on some website like www.cppreference.com if you don't know them.

Remove whitespace in C++ string doesn't work [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have read these two questions already:
Remove spaces from std::string in C++
remove whitespace in std::string
For some reason, I can never get the solutions to work correctly. In my program, I collect input from the user and pass it to an std::string. From there, I want to remove all of the spaces in it. For example, if the user inputs "3 + 2", I would like it to change to "3+2".
What happens is, whatever is before the first string is kept. Here is my program:
#include <iostream>
std::string GetUserInput() {
std::cout << "Please enter what you would like to calculate: ";
std::string UserInput;
std::cin >> UserInput;
return UserInput;
}
int PerformCalculation(std::string Input) {
Input.erase(std::remove_if(Input.begin(), Input.end(), ::isspace), Input.end());
std::cout << Input;
return 0;
}
int main() {
std::string CalculationToBePerformed = GetUserInput();
int Solution = PerformCalculation(CalculationToBePerformed);
return 0;
}
So when I run this program and type in "3 + 2", the output is "3".
Here is my console:
Please enter what you would like to calculate: 3 + 2
3
Process finished with exit code 0
I cannot figure out how to resolve this. I even tried using a solution that involved using a regex to remove all the \s characters, and that gave me the same issue.
To read the complete line (up to terminating \n), you need to use e.g. std::getline(std::cin, UserInput);. Otherwise, you're currently reading text up to first whitespace character.

My codes work well In Dev c++ IDE, but in linux terminal, it doesn't. (especially in the part of 'while' loop.) [closed]

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 6 years ago.
Improve this question
while(true) {
getline(myfile, a[i]);
if (a[i]=="")//or if(a[i].empty())
break;
i++;
n = i;
}
In this while loop, when getline function gets a blank line from myfile object (there is a blank line between a series of binary numbers).
Example:
101010
000
11
1
00
<- when getline meets this line, by "if" break; has to work.
0011
10
00111
1101
But, it doesn't realize that blank line.
What is wrong?
What should I code to break when getline() meets the blank line?
I do this through PuTTY.
You are most likely running into the NL/CR issue.
Instead of
if (a[i]=="")
Use something like:
if (isEmptyLine(a[i]))
where
bool isEmptyLine(std::string const& s)
{
for ( auto c : s )
{
if ( !std::isspace(c) )
return false;
}
return true;
}
You can also convert the file into a file with UNIX style line endings by using a utility called dos2unix. That should also fix the problem.

what is the time complexity of this program? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I'm new to time complexity in algorithms.
This is the code for counting the number of words in a text file.
My problem is that every time my program prints one more than the actual count of words in the file, like if I have 11 words in my file it prints 12.
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
/* main function */
void main()
{
ifstream inFile; //file file name
string fileName;
string word;
int count = 0;
inFile.open("example.txt");
while(!inFile.eof())
{
inFile >> word;
++count;
}
cout << "Number of words in file is " << count<<endl;
inFile.close();
}
//this file is for counting the number of words in a text file**
First thing first : Why is iostream::eof inside a loop condition considered wrong? This will answer your extra count problem.
Then, coming to complexity, since it will go though every N words till it reaches end of file, it will be done in O( N ) time
Also, void main() is not legal c++, main should return int

Strcmp() function not working properly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
ifstream myfile;//file reading mode
myfile.open("file2.txt");//file opened
if(!myfile)
{
cout<<"your file cannot be opened";
}
for(;!myfile.eof();)
{
myfile>>name>>salary>>concerned_department;
cout<<name<<"\t"<<salary<<"\t"<<concerned_department<<"\n";
}
do
{
cout<<"To search an employee please enter the name of the employee<<"\n";
cin>>empName;//will take the string from the user.
cout<<empName<<"\n";
ifstream myfile;//file reading mode
myfile.open("file2.txt");//file opened successfully
if(strcmp(name,"empName")==0)//here the main problem lies
{
myfile>>name>>salary>>concerned_department;
cout<<name<<"\t"<<salary<<"\t"<<concerned_department<<"\n";
}
else
{//
cout<<"ERROR "could not be compared"<<"\n";
}
cout<<"Do you want to continue (y/n)";
cin>>con;
}
while(con=='y');
The strcmp() function is not comparing the strings though given. string1 is given in the file whereas the string2 is being taken from the user.
Use the following code:
if(strcmp(name,empName)==0)
{
...
}
Note that there must be no quotation marks around empName to compare its contents.