streaming into string and char
Jun 16, 2017 at 7:33pm UTC
i have a text file called numbers.txt with the following content:
4 a astring
i want to stream into the char ch the letter 'a'
and stream into string s 'astring'
and display the output , but it is not working.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
# include <iostream>
# include <fstream>
# include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("numbers.txt" );
if (inFile.fail())
{
cerr << "error opeining file" << endl;
exit(1);
}
int x, y;
string s;
char ch[1];
inFile >> x >> y;
cout << "num 1 " << x << endl;
cout << "num 2 " << ch << endl;
cout << "num 3 " << s << endl;
system("pause" );
return 0;
}
Jun 16, 2017 at 8:13pm UTC
Hello masterinex,
Try this:
1 2 3 4 5 6 7 8 9 10 11
int x;
string s;
char ch[1];
inFile >> x >> ch;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' ); // <--- Needs the "limits" header file. To clear the \n from the input buffer after a cin >>.
std::getline(infile, s);
and see what happens.
Hope that helps,
Andy
Jun 16, 2017 at 8:43pm UTC
i have a text file called numbers.txt with the following content:
4 a astring
i want to stream into the char ch the letter 'a'
and stream into string s 'astring'
1 2 3 4
int x, y;
string s;
char ch[1];
inFile >> x >> y;
You are simply not reading the char.
If the file is
number character string you need to read
inFile >> x >> ch >> s;
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
void waitForEnter();
int main()
{
std::ifstream infile("numbers.txt" );
if (!infile)
{
std::cerr << "\nError opening file\n" ;
exit(1);
}
int x;
char ch;
std::string s;
// File format is:
// 4 a string
// i.e. integer char string
// So I need to stream all the three components:
infile >> x >> ch >> s;
std::cout << "number read: " << x << '\n' ;
std::cout << "character read: " << ch << '\n' ;
std::cout << "string read: " << s << '\n' ;
waitForEnter();
return 0;
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n" ;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
}
Writing only
, without adding the wrong output or the errors, is not of much help.
Topic archived. No new replies allowed.