Hey guys,
I have a question as you can see in the code below I am trying to read a digit from a txt file and save it into an array/variable. I have a txt file which looks like this:
#include <iostream>
#include <fstream>
int Z1;
int main() {
std::ifstream myFile;
myFile.open("Random.txt");
if (!myFile){
std::cerr << "Data could not be opened!\n";
}
else{
//for (i = 0;)
myFile.seekg(10, std::ios::beg);
myFile >> Z1;
myFile.close();
std::cout << Z1;
}
return 0;
}
The code works fine for a one-digit but for a double-digit it doesn't work. So I thought maybe there is a way to say "myFile.seekg(7-10, std::ios::beg);" or something like this. Is there any way to do it like this and how is the usual way to read a x-digit number from a txt file?
I searched google and some people say you should use a buffer to read the digits into and then save them into a variable/array but isn't there a shorter way?
If that's the exact contents of the file, then I would just do something like this:
1 2 3 4 5 6 7 8 9 10
std::string str;
int n1, n2;
char ch;
while (myFile >> str >> n1 >> ch >> n2)
{
// 'str' now contains the string "Number"
// 'n1' contains the first number
// 'ch' contains the letter 'K'
// 'n2' contains the second number
// ... Your code here ...
Hey,
sry for the late answer but thanks for your help. It works great :)
But I have a question depending the code. Why is it necessary to use a forever loop and is this a clean/good way to program this.
My Code looks now something like this: while (myFile >> array[0][0] >> array[1][0] >> array[2][0]...array[16][1]
I learned I should use the shortest code as possible and as many loops as possible. But it seems to me like this are a lot of declarations isn't this eating a lot of resources or am I thinking wrong?