Reading integers from an unorganized text file - c++

#include <iostream>
#include <fstream>
#include <string>
#include <cctype> // isdigit();
using namespace std;
int main()
{
ifstream fin;
fin.open("Sayı.txt");
while (!fin.eof()){
string word;
int n;
fin >> word; //First i read it as a string.
if (isdigit(word[0])){ //checks whether is it an int or not
fin.unget(); //
fin >> n; // if its a int read it as an int
cout << n << endl;
}
}
}
Suppose the text file is something like this:
100200300 Glass
Oven 400500601
My aim is simply to read integers from that text file and show them in console.
So the output should be like
100200300
400500601
You can see my attempt above.As output i get only the last digit of integers.Here's a sample output:
0
1

Simple just try converting the string read to an int using string streams, if it fails then it isn't an integer , otherwise it is an integer.
ifstream fin;
istringstream iss;
fin.open("Say1.txt");
string word;
while (fin>>word )
{
int n=NULL;
iss.str(word);
iss>>n;
if (!iss.fail())
cout<<n<<endl;
iss.clear();
}

I think the following should do what you want (untested code):
int c;
while ((fin >> std::ws, c = fin.peek()) != EOF)
{
if (is_digit(c))
{
int n;
fin >> n;
std::cout << n << std::endl;
}
else
{
std::string s;
fin >> s;
}
}

Related

Get more values with istringstream

When I input [1,0,0,1,0] I get output with 1 0 0 1 0 0, I don't know why there is an extra zero and why the while loop doesn't terminate after ].
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string str;
std::istringstream is;
std::vector<int> numbers;
std::getline(std::cin, str);
is.str(str);
char ch;
is >> ch;
while (!is.eof())
{
int num;
is >> num >> ch;
numbers.push_back(num);
}
for (auto num : numbers)
std::cout << num << " ";
std::cout << std::endl;
return 0;
}
Change the while loop part will get expected behavior:
int num;
while (is >> num >> ch) {
numbers.push_back(num);
}
The eof check is misused here, so the last character read failed and get a default number 0. Read this answer for more details:
https://stackoverflow.com/a/4533102/1292791

C++ - Taking variable number of integers from standard input, n number of times

I'm not able to figure out why the loop in following program is not running exactly testCount times. Please help to make it correct.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
string instr;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}
Thanks. I got it. The problem is with getline(). First loop cycle is getting wasted as getline() is taking first line containing just new line character when I pressed enter key after typing testCount value.
std::ws is an input stream manipulator which ignores all whitespaces to the point where the first non-whitespace character is encountered.
Also, getline leaves whitespaces where they are if they don't fit in the line. cin >> ws will discard those.
Here's the bullet proof code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount >> ws;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
cout << "testCount " << testCount << endl;
string instr;
cin >> ws;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}

Reading from input file and storing in array c++

I want to read from a file.txt that looks like this:
process_id run_time
T1 23
T2 75
Read each line and store integers of run time (tab separation)in an array
My problem now is to read the content of the file .. and how to get the integer after the tab separation?
thanks
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
int process_id[100];
int run_time[100];
int arrival_time[100];
char quantum[50];
int switching;
char filename[50];
ifstream ManageFile; //object to open,read,write files
cout<< "Please enter your input file";
cin.getline(filename, 50);
ManageFile.open(filename); //open file using our file object
if(! ManageFile.is_open())
{
cout<< "File does not exist! Please enter a valid path";
cin.getline(filename, 50);
ManageFile.open(filename);
}
while (!ManageFile.eof())
{
ManageFile>>quantum;
cout << quantum;
}
//ManageFile.close();
return 0;
}
use C++, not C
don't use std::cin.getline, use std::getline (it works with std::string and is safer)
use a vector instead of hard-dimensioned arrays
use a vector of struct instead of "corresponding arrays"
don't use while (!stream.eof())
Here's a sample that might be helpful:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct Record {
int process_id;
int run_time;
int arrival_time;
};
int main() {
std::vector<Record> records;
int switching;
std::string filename;
ifstream infile;
while (!infile.is_open()) {
cout << "Please enter your input file: ";
std::getline(std::cin, filename);
infile.open(filename); // open file using our file object
cout << "File cannot be opened.\n";
}
std::string quantum;
std::getline (infile, quantum); // skip header row
while (std::getline(infile, quantum)) {
// e.g.
Record current;
std::istringstream iss(quantum);
if (iss >> current.process_id >> current.run_time >> current.arrival_time)
records.push_back(current);
else
std::cout << "Invalid line ignored: '" << quantum << "'\n";
}
}
You can try something like this:
while (!ManageFile.eof())
{
quantum[0] = 0;
ManageFile>>quantum;
if (strcmp(quantum, "0") == 0 || atoi(quantum) != 0)
cout << quantum << endl;
}
Of course, you need to include in the head
Use function ignore from istream [http://www.cplusplus.com/reference/istream/istream/ignore/]
while (!ManageFile.eof())
{
std::string process_id;
int run_time;
ManageFile >> process_id;
ManageFile.ignore (256, '\t');
ManageFile >> run_time;
}
Using fscanf instead of ifstream can make the job a lot easier.
char str[100];
int n;
....
fscanf(FILE * stream,"%s %d", str, &n);
You will get the string in str and integer in n.

Variables Not Updating From istringstream

So, I've got code like the following:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
char c;
ifstream f("test.txt");
char n;
char z;
char o;
int output;
istringstream in;
string line;
while (getline(f, line))
{
in.str(line);
do
{
c = in.get();
}
while (isspace(c));
in.unget();
in >> n >> c >> z >> c >> o >> c >> output;
cout << n << z << o << output << endl;
in.str(string());
}
f.close();
return 0;
}
and the file test.txt contains:
A,B,C,1
B,D,F,1
C,F,E,0
D,B,G,1
E,F,C,0
F,E,D,0
G,F,G,0
The format of each line in the text file is "char,char,char,bool" (I'm ignoring the fact that there may be whitespace in the middle of the line, for now).
When I compile and run this code ((using Visual Studio 2010), I get:
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1
ABC1
Obviously, this isn't what I want. Does anyone have an answer as to what's going on here?
A quick fix, put istringstream inside the loop to reset the input indicator:
//istringstream in; ----------+
string line; |
while (getline(f, line)) |
{ |
istringstream in; <--------+
in.str(line);
do
{
c = in.get();
}
while (isspace(c));
in.unget();
in >> n >> c >> z >> c >> o >> c >> output;
cout << n << z << o << output << endl;
//in.str(string()); <-------------------- you can remove this line
}
f.close();
If you don't reset the input indicator, the in.get will not work as you expect. or you can simply use seekg(0)
When you change the content of the stringstream, by default it will set the position pointer to the end of the stream: http://www.cplusplus.com/reference/sstream/stringstream/str/. Add in.seekg(0); after in.str(line); and it should work:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
char c;
ifstream f("test.txt");
char n;
char z;
char o;
int output;
istringstream in;
string line;
while (getline(f, line))
{
in.str(line);
in.seekg(0);
do
{
c = in.get();
}
while (isspace(c));
in.unget();
in >> n >> c >> z >> c >> o >> c >> output;
cout << n << z << o << output << endl;
in.str(string());
}
f.close();
return 0;
}

Reading Numbers from a File

I have a file with many numbers. The file looks like "192 158 100 0 20 200" basically like that. How can I load the files number values 1 at a time and display them on the screen in C++?
try something like this:
int val;
std::ifstream file("file");
while (file >> val)
std::cout << val;
The following program should print each number, one per line:
#include <iostream>
#include <fstream>
int main (int argc, char *argv[]) {
std::ifstream ifs(argv[1]);
int number;
while (ifs >> number) {
std::cout << number << std::endl;
}
}
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
int main() {
std::ifstream fs("yourfile.txt");
if (!fs.is_open()) {
return -1;
}
// collect values
// std::vector<int> values;
// while (!fs.eof()) {
// int v;
// fs >> v;
// values.push_back(v);
// }
int v;
std::vector<int> values;
while (fs >> v) {
values.push_back(v);
}
fs.close();
// print it
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Please consider the following code:
ifstream myReadFile;
myReadFile.open("text.txt");
int output;
if (myReadFile.is_open())
{
while (fs >> output) {
cout<<output;
}
}
//Of course closing the file at the end.
myReadFile.close();
As well, please include the iostream and fstream inside your code when using the example above.
Note that you need to start open a filestream to read and you can try to read it char by char and detect is there any white space in between it.
Good luck.
Another way of doing it:
std::string filename = "yourfilename";
//If I remember well, in C++11 you don't need the
//conversion to C-style (char[]) string.
std::ifstream ifs( filename.c_str() );
//Can be replaced by ifs.good(). See below.
if( ifs ) {
int value;
//Read first before the loop so the value isn't processed
//without being initialized if the file is empty.
ifs >> value;
//Can be replaced by while( ifs) but it's not obvious to everyone
//that an std::istream is implicitly cast to a boolean.
while( ifs.good() ) {
std::cout << value << std::endl;
ifs >> value;
}
ifs.close();
} else {
//The file couldn't be opened.
}
The error-handling can be done in many ways through.