Reputation: 67
I have a simple problem with reading the file. I am trying to open a file which is included to the resource files as .txt file. The problem appear when I am trying to compile it and print it from the structure.
#include <iostream>
#include <fstream>
struct mystruct
{
double x, y;
int a;
};
int main()
{
using namespace std;
ifstream file("file.txt");
double x, y;
int a;
if (file.is_open()) {
while (file >> x >> y >> a)
{
mystruct m;
m.x;
m.y;
m.a;
cout << m.x << endl << m.y << endl << m.a << endl;
}
}
else
cout << "Cannot open the file";
return 0;
}
I am using that wired shifting because in my file I have three different values which I have to store for three different variables in my structure.
Why my file is not visible and cannot be opened?
Here is the link to file.txt source: http://wklej.org/hash/05290721372/
And also here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.3)
project(reading_from_file)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(reading_from_file ${SOURCE_FILES})
Maybe here is the problem why the file is not visible.
Thank you for the help!
Upvotes: 0
Views: 124
Reputation: 66210
First of all: sorry for my bad English.
Second: are you sure that file.txt is in the right directory?
And what about read permission? Try with
chmod ugo+r file.txt
To me it works; or, at least, it opens the file.
However, I do not think the program is working as you expect: it reads the values but prints, each time, the three random values which are inizialized in the members of 'm'.
You should change it this way
ifstream file("file.txt");
if (file.is_open()) {
mystruct m;
while (file >> m.x >> m.y >> m.a)
cout << m.x << endl << m.y << endl << m.a << endl;
}
else
cout << "Cannot open the file";
Upvotes: 2