Im trying to put Intergers from textfile into array, and ive been writing a code for it but only works if i have intergers in textfile and not with characters and intergers.. What do i have to change?
Textfile can look like this (not working):
Chris Andersson
15
Theres Green
20
int *data;
int num = 0;
ifstream In("file.txt"); //
if (In.good())
{
int d;
while (In >> d) num++; // count values from file
In.close();
data = newint[num]; // create dynamic array
In.open("file.txt");
for (int i=0; i < num; i++) // read it to array
In >> data[i];
In.close();
}
else
{
cout << "could not open file.txt" << endl;
return 0;
}
// Write it out to check if everything is alright!
for (int i=0; i < num; i++)
cout << data[i] << endl;
you would need to read the file line by line and then check if the value is an integer.
if it is put it in your array
if else discard and it and go to the next line.
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
usingnamespace std;
int main()
{
// storage for your data
vector<int> data;
ifstream In("file.txt");
if (In.good())
{
string line;
while (getline(In,line)) // while it is still not the end of file
{
std::cout << line << std::endl;
// simple check to see if the string size is greater than 4
if(line.size() > 4)
{
// dont do anything if string is greater than 4
}
else
{
try
{
// convert a string to an int
stringstream temp;
temp << line;
int data_val;
temp >> data_val;
// insert to the end of the vector
data.push_back(data_val);
}
catch(exception &e)
{
// display error
std::cout << e.what() << std::endl;
}
}
}
In.close();
cout << endl;
// double check you read all your data
for (auto i: data)
{
cout << i << endl;
}
}
else
{
cout << "could not open file.txt" << endl;
return 0;
}
int x;
cin >> x;
return 0;
}