C++ : Read form text file and convert to int problem? - c++

I have this code that reads from marks.txt file.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string name,result;
int number1;
ifstream myfile ("marks.txt");
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline (myfile,name,'\t');
getline (myfile,result,'\t');
stringstream(result) >> number1;
cout << number1;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
with my marks.txt file consists of:
john 20
But when i ran the program. Number1 output is 36. How can i convert result string to int correctly??

Note that you're passing \t (tab character) as the delimiter to getline. Are you sure you are using a tab in your input file? If you use a space or any other character, all the input will go into name and your result will be empty, which will leave number1 undefined. I suspect that's the reason you're getting 36 out of nowhere.

Related

How do i compare two text files in c++

okay I've searched everywhere and couldn't get my hand on it so ..
i'm doing a library system where a librarian enters his username and the program checks if he is one of the librarians or not
i'm stuck on the comparing part , i tried using getline but it gave me an error , tried gets_s and used a char array instead of a string and still didn't work
kindly help me with what i should do
using namespace std;
#include <iostream>
#include <string>
#include <fstream>
int main()
{
//opening files
ifstream readUsername;
ofstream enterUsername;
//variables
string existUsername;
string enteredUsername;
//reading files
readUsername.open("librarian usernames.txt");
if (readUsername.fail())
{
cout << "can't open file" << endl;
}
enterUsername.open("entered librarian username.txt");
if (enterUsername.fail())
{
cout << "can't open file" << endl;
}
while(!readUsername.eof)
{
readUsername >> existUsername;
}
enterUsername << enteredUsername;
readUsername.close();
enterUsername.close();
enterUsername.clear();
system("pause");
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
infile.open("listOfWords.txt"); //open file
for(string listOfWords; getline(infile, listOfWords, '.'); ) //read sentences including
//spaces
cout<<listOfWords; //this displays
return 0;
}
This shows you how to output the text so you should just save both files to a variable then compare the variables.

Numbering Lines in a File With C++

I wrote a quick C++ program that asks the user for a input text file and an output text file. The program is then supposed to number the lines in the file on the left margin. However, I cannot seem to get it working properly, it compiles fine but does not number the lines like it is supposed to. I believe it is a logical error on my part. I am also not too familiar with file i/o in C++ as I am just learning it now using old school textbooks.
Here is the file:
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{int i = 0 , num = 1;
string inputFileName;
string outputFileName;
string s;
ifstream fileIn;
ofstream fileOut;
char ch;
cout<<"Enter name of input file: ";
cin>>inputFileName;
cout<<"Enter name of output file: ";
cin>>outputFileName;
fileIn.open(inputFileName.data());
fileOut.open(outputFileName.data());
assert(fileIn.is_open() );
assert(fileOut.is_open() );
while (!(fileIn.eof()))
{ch=fileIn.get();
if (ch=='\n') num++;
fileOut << num << "\n";
s.insert(i,1,ch); //insert character at position i
i++;
}
fileOut << s;
fileIn.close();
fileOut.close();
return 0;
}
If anyone could point me in thr right direction or give me some tips I would be eternally grateful.
int i = 0;
string line;
while (getline(infile, line))
{
outfile << (i++) << " " << line << "\n";
}

Opening a file; but skipping each line

I wanted to know how you skip lines as you open the file with fstream. when I open the file it returns all the numbers bunched up together like "201051535402530"
here is my code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string testing;
ifstream myfile;
myfile.open ("inputfile");
while (!myfile.eof())
{
getline(myfile, testing);
cout << testing;
}
return 0;
}
the inputfile is listed as:
20
10
5
15
35
40
25
30
When getline() reads a line, it discards the trailing newline. If you want one printed in your output, you need to put it there yourself:
cout << testing << endl;

Read text file display to console then append text file

I have a text file of names. I want to read the text file into a stream, display it to the console. When it is done, it will prompt the user to enter their name. It should then add it to the file.
I can get it to do both of these things separately but not together.
Here is my code.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
fstream myfile;
string line;
string name;
myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
if (myfile.is_open())
{
while( getline(myfile, line) )
{
cout << line << endl;
}
cout << "Enter your name!\n";
getline (cin, name);
myfile << name;
myfile.close();
}
else
{
cout << "file was not opened\n";
}
return 0;
}
If I leave the while loop in there, it writes all the names to the console, but doesn't append the user entered name to the list. If I take out the while loop, I can add a name to the file but then of course I am not getting a list of the names that are already in that file.
My best guess is, I think it might have something to do with the fact that after I loop through the file using getline, The position is at the end of my stream, so when I try to add a name to it, there isn't any room left in the stream?
Your guess is correct.
The last call to getline() (the one that failed) set the error flags on your stream, which will fail any further IO attempts, which is why nothing is actually written in your file.
You can reset the errors flags with clear() after your reading loop :
myfile.clear();
Note:
You should also test for the returned value of your last getline() call.
Just bumped in to this issue and even though there is accepted answer here I think one can use full code that shows how to use canonical C++ file reading loop:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
fstream myfile;
string line;
string name;
myfile.open("Names.txt",ios::out | ios::in | ios_base::app);
if (myfile.is_open())
{
while( getline(myfile, line) )
cout << line << endl;
if (file_list.eof())
file_list.clear(); //otherwise we can't do any further I/O
else if (file_list.bad()) {
std::cout << "Error occured while reading file";
return 1;
}
cout << "Enter your name!\n";
getline (cin, name);
myfile << name;
myfile.close();
}
else
{
cout << "file was not opened\n";
}
return 0;
}

How to open any input file whether it contains words or numbers and prints it out. C++

So Lets say this is what the input file contains
12
Hello
45
54
100
Cheese
23
How would I print it out on the screen in that order.
This is what I had but it skips some lines.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
string word;
int loop = 0;
ifstream infile;
infile.open("arraynumbers.txt");
while(infile >> number >> word)
{
if( infile >> number)
{
cout << number << endl;
}
if(infile >> word)
{
cout << word << endl;
}
}
return 0;
}
I suggest using www.cplusplus.com to answer these questions.
However, you are on the right track. Since you are just outputting the contents of the file to stdout, I suggest using readline() and a string. If you need to access the numeric strings as ints, use the atoi() function.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream file("arraynumber.txt");
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else cout << "Error opening arraynumber.txt: File not found in current directory\n";
return 0;