[英]Sorting out int variables from a .txt file (fstream, c++)
I have a.txt file with these this line on the top '12 4 25 257'
each of the numbers spaced out by a ' '
and the line ends with '\n'
我有一个 .txt 文件,此行位于顶部'12 4 25 257'
中,每个数字之间用' '
隔开,行以'\n'
结尾
I have these variables and a function getFirstLine
:我有这些变量和一个 function getFirstLine
:
int A;
int B;
int C;
int D;
ifstream File("a.txt");
void getFirstLine(int &A, int &B, int &C, int &D)
{
int list[] = {A, B, C, D};
string myText;
getline(File, myText);
int size = myText.size();
cout << size;
for (int i = 0; i < size; i++)
{
if (myText[i] != ' ')
{
list[i] = (int)myText[i] - 48;
cout << list[i] << endl;
}
}
}
I want to basically save the first number on A, second on B, third C etc...我想基本上将第一个数字保存在 A 上,第二个保存在 B 上,第三个 C 等...
I cant seem to get this working sadly:( Can someone help me with this?可悲的是,我似乎无法正常工作:(有人可以帮我吗?
Output should look like: Output 应如下所示:
A = 12,
B = 4,
C = 25,
D = 257,
Maybe something like this?也许是这样的?
std::string line;
std::getline(file, line);
line = line.substr(1, line.length() - 2);
std::istringstream iss(line);
iss >> A >> B >> C >> D;
#include<iostream>
#include<vector>
#include<ifstream>
using namespace std;
struct pairs
{
char ch;
int value;
};
int main()
{
vector<pairs> store;
ifstream is("koord.txt");
pairs temp;
char ch = 'A';
while (is)
{
temp.ch = ch;
is >> temp.value;
store.push_back(temp);
}
for (int i = 0; i < store.size(); ++i)
{
cout << store[i].ch << " " << store[i].value << endl;
}
return 0;
}
you can use this.你可以用这个。 But if you read more entries char will overflow.但是,如果您阅读更多条目,char 将会溢出。 you can use string instead of char.您可以使用字符串而不是字符。
This is what I ended up doing, might not be the most efficient way of doing it but it seems to work.这就是我最终要做的,可能不是最有效的方法,但它似乎有效。 But I will look into std::istringstream
.但我会调查std::istringstream
。 It seems like good way to do it.这似乎是一个好方法。
void getFirstLine(int &A, int &B, int &C, int &D)
{
string myText;
string temp;
vector<int> save;
int size = myText.size();
getline(File, myText); //get the first line of text not including \n
for (int i = 0, j = 0, size = myText.length(); i < size; i++)
{
temp.push_back(myText[i]); //adds the myTest[i] to the end of temp
if (myText[i] == ' ')
{
save.push_back(stoi(temp)); //stoi(temp) to an int --> push_back appened to save at the end
j++;
temp.clear();
}
if (i == (size - 1)) //because the end of the line doesnt have a space
{
save.push_back(stoi(temp));
j++;
temp.clear();
}
}
for (int i = 0; i < 5; i++){
cout << "list "<< i << ": "<< save[i] << endl;
}
//retruning the values
A = save[0];
B = save[1];
C = save[2];
D = save[3];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.