微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 .txt 文件fstream,c++中整理出 int 变量

如何解决从 .txt 文件fstream,c++中整理出 int 变量

我有一个 .txt 文件,这些行在顶部 '12 4 25 257',每个数字由 ' ' 隔开,该行以 '\n' 结束

我有这些变量和一个函数 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;
        }
    }
}

我想基本上保存 A 上的第一个数字,B 上的第二个,C 上的第三个等等...

我似乎无法悲伤地工作:( 有人可以帮我解决这个问题吗?

输出应如下所示:

A = 12,B = 4,C = 25,D = 257,

解决方法

也许是这样?

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;
    }

你可以使用这个。但是如果你读了更多的条目,char 就会溢出。您可以使用字符串代替字符。

,

这就是我最终要做的,可能不是最有效的方法,但它似乎有效。但我会研究std::istringstream。这似乎是一个很好的方法。

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];
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。