Reading file into array C++ - c++

I am trying to simply read a file "input.txt" into an array people[]. The txt file has 3 numbers:
10
20
30
I am getting -9.25596e+61 instead of 10 for people[0]. Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Trip {
private:
double people[3];
public:
void readFile(string file);
};
void Trip::readFile(string file) {
ifstream input;
input.open(file);
input >> people[0] >> people[1] >> people[2];
cout << people[0];
input.close();
}
int main() {
Trip trip;
trip.readFile("input.txt");
return 0;
}

Your program is correct. Working fine.
Currently, it is not getting the file. So, it is failing for you.
Provide the fully qualified path to readFile() as below example:
Path like "C:\\Users\\source\\Temp\\x64\\Debug\\input.txt"
Windows support file path with backward or forward slashes:
msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx

Related

Using fstream doesn't write results

I have a problem with fstream. It takes data from one file but usually it doesn't write it in a result file. I didn't have this problem before and I hadn't changed anything in settings when this started happening. Also restarting computer used to do the trick and it would start working but not anymore.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in("in.txt");
ofstream out("out.txt");
int a;
in >> a;
out << a;
in.close();
out.close();
return 0;
}
if I write cout << a; it shows the number that was in data file, but with out >> it doesn't change the result file out.txt. All files are in the same folder.
If it makes a difference: I'm using codeblocks

Getting Information from input file C++

I'm pretty new to coding so I'm not entirely sure if I'm doing file extraction correct. I'm getting lldb as my output for this code. Instead of prompting the user with the words in the hangman.dat file.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream sourceFile;
sourceFile.open("hangman.dat");
if (sourceFile.fail())
{
cout<<"File didn't open" ;
}
else
{
string words;
sourceFile >> words;
while(sourceFile>>words)
{
cout<<words<<endl;
}
}
}
The file hangman.dat contains the following information:
Fall
leaves
Thanksgiving
pumpkins
turkey
Halloween

Reading from text file to structure

Firstly, I'd like to explain what I'm trying to do. So, I have a text file with 10 names followed by their points. I'm trying to create a structure and read information from a file using a function (void). And that's my code and text file:
code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void read(struct laLiga t[]) {
ifstream infile("info.txt");
int i = 0;
while(infile >> t.team[i] >> t.points[i]) {
infile.get(t.team);
infile >> t.points;
i++;
}
}
struct laLiga {
char team[50];
int points;
};
int main() {
struct laLiga t[10];
read(t);
return 0;
}
text file:
Athletic Bilbao 15
Atletico Madrid 18
Barcelona 16
Alaves 10
Las Palmas 12
Real Madrid 18
Real Sociedad 10
Sevilla 17
Eibar 11
Villarreal 16
First of all, you need to define the structure before you use it in the read function.
Secondly, in the read function it is the variable t that is an array, not its members. So you should be using t[i].team and t[i].points.
Thirdly, you have already read the data from the file with the >> operators in the loop condition. You should not read it again inside the loop.
Fourthly, the input file you want to read is actually harder to parse than you think. That is because you can have names both without and with spaces in them. Both the get function of input streams and the input operator >> separates on spaces. You should probably read the whole line and then split it at the last space.
Lastly, and actually a reason I should not write an answer is that you haven't actually asked a question, or told us what is wrong with your code. Please read about how to ask good questions for future questions.
You could use std::vector to make things easier:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
using namespace std;
auto file_text =
R"(Athletic Bilbao 15
Atletico Madrid 18
Barcelona 16
Alaves 10
Las Palmas 12
Real Madrid 18
Real Sociedad 10
Sevilla 17
Eibar 11
Villarreal 16)";
struct laLiga {
std::string team;
int points;
};
void read(std::vector<laLiga>& t) {
//ifstream infile("info.txt"); // would also work
std::stringstream infile{file_text};
while(infile) {
laLiga laliga{};
std::string partial_team_name{};
while(!(infile >> laliga.points)) { // keep going until we get the points
infile.clear(); // we could not read points, infile stream now in error; clearing to continue
if(infile >> partial_team_name) // maybe the next string is part of a team name
laliga.team += (laliga.team.empty() ? "" : " ") + partial_team_name; // add to team name with space if there was something already in there
else
return; // no points, no team, we're done
}
t.push_back(laliga); // after we get the points we can add the team
}
}
int main() {
std::vector<laLiga> t;
read(t);
for(auto i : t) {
std::cout << std::setw(30) << i.team;
std::cout << std::setw(10) << i.points << '\n';
}
return 0;
}
Output:
Athletic Bilbao 15
Atletico Madrid 18
Barcelona 16
Alaves 10
Las Palmas 12
Real Madrid 18
Real Sociedad 10
Sevilla 17
Eibar 11
Villarreal 16
live demo
if you want to read or write structs in a text file then best would be to use ifstream read() function and ofstream write() function. Following is how to use them.
#include <iostream>
#include <fstream>
#include <cstring> // for strncpy()
using namespace std;
struct laLiga {
char team[50];
int points;
};
int main()
{
struct laLiga t;
strncpy(t.team,"Some Name",sizeof("Some Name"));
t.points = 100;
//do this for writing a complete struct to a text file at once
ofstream output("info.txt");
output.write(reinterpret_cast<char*>(&t),sizeof(t));
output.close();
//do this for reading a complete struct from a text file at once
struct laLiga T;
ifstream input("info.txt");
input.read(reinterpret_cast<char*>(&T),sizeof(T));
input.close();
//now T will hold both the name and points fields from the text file without doing it individually
cout << "Name = " <<T.team << endl;
cout << "Points = " << T.points << endl;
return 0;
}
OUTPUT (Console)
Name = Some Name
Points = 100
Both read() and write() function's first parameter should be char* that is why we use reinterpret_cast to cast the complete struct to sequence of bytes and then write to file.
Only drawback of doing like this is that the text file will be unreadable when opened in windows as it wont be normal text but reading and writing would be much easier.

Not Fully read from the text file

I am trying to read some integer numbers from a text file in C++. It is weird problem that it reads only 13 numbers , but my file contains 25 numbers . I searched but not found any thing , someone suggested to add ios::binary , but not working.
Why ??
here is this part of code.
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("Nvector.txt");
vector<int> N;
for(int j=0; j<25; j++)
{
int input;
myfile>> input;
N.push_back (input);
}
system("PAUSE");
return 0;
}
You might want to check the text file that you're reading from, there can be special end of line characters that will cause the integers to be concatenated/removed from the vector, there might also be problems related to the vector

the output is not what i typed.It is --> (畳慨汩朠灵慴찀쳌쳌쳌)

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
char x[20];
cout << "enter something\n";
cin.getline(x,20);
ofstream o("d:/tester.txt");
//o.write( (char*)&x , sizeof(x) );
for(int i = 0 ; i<=19 ; i++ ) {
o.put(x[i]);
}
}
I am not getting that output in the file the one which i enter during program . for eg. the output is 畳慨汩朠灵慴찀쳌쳌쳌 on writing suhail gupta.
What is the problem with the code ? Even when i use o.write( (char*)&x , sizeof(x) ); (the commented statement) i get the same output.
What is the reason?
Your program involves undefined behavior. The x array is not fully initialized and you read from the uninitialized indices. Besides, you always write 20 bytes, independent of what you read from the user.
I guess you use some text editor like Notepad. The latter has bugs when trying to guess the encoding. It appears that it guesses the file is UTF16 and displays 20/2 == 10 characters instead.
To solve the problem, store to the file exactly the number of characters entered by the user. Use std::string to make it easier.
Edit: The C++ way:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string x;
cout << "enter something\n";
getline(cin, x);
ofstream o("d:/tester.txt");
o << x;
}