Help - load numbers from a .txt file to variables (c++)
Program 2 should show 111, 2开发者_开发知识库22 and 333 as result for x,y,z. I want to read the text file, line to line, and save one line to one variable like: Line1 = x Line2=y Line3 =z Can someone help me?
PROGRAM 1
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
float x, y, z;
int main()
{
x=111;
y=222;
z=333;
ofstream meuarquivo;
meuarquivo.open ("brasil.txt");
meuarquivo << x << "\n";
meuarquivo << y << "\n";
meuarquivo << z << "\n";
meuarquivo.close ();
return 0;
}
PROGRAM 2
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
float x, y, z;
int main(){
x=0;
y=0;
z=0;
char nomedoarquivo[90];
ifstream objeto;
cin.getline (nomedoarquivo, 90);
objeto.open (nomedoarquivo);
if (!objeto.is_open ()){
exit (EXIT_FAILURE);}
while (objeto.good()){
string r;
objeto >>r;
}
cout << "\n" << x << "\n" << y << "\n" << z << "\n";
return 0;
}
The second program needs to read input from a file. But the program isn't opening the file the first program has written to.
- Have a std::vector to store the strings that are read from file.
- Open the file in read mode, which the first program has written text to, as a part of first program.
push_back
the each read string to the vector until the end of file is reached.Iterate through the vector and convert
std::string
usingatoi
.int readNumber = atoi((*iter).c_str()) ;
This should give you an idea.
The code segment
while (objeto.good()){
string r;
objeto >>r;
}
basically means that you are reading in each number as a string, and discarding it immediately when the loop scope ends. Instead I would suggest creating an float array of size three, reading into them using the loop, and then assigning the values of each of the elements to x, y and z, like so:
float vals[3];
int i = 0;
while (objeto.good()) {
objeto >> vals[i];
i++;
}
x = vals[0]; y = vals[1]; z = vals[2];
精彩评论