![](/img/trans.png)
[英]Understanding How to Read Into A File & Separate Lines from File into Different Variables
[英]How to read a line from text file and separate them in different variables?
這是我的示例文本文件, 在此處輸入圖像描述
1 Class Physics American 3.6 5 Maria Garcia 1-541-754-3010
2 Class Chemical Australian 3.5 4 Maria Hernandez 1-541-754-3233
我有一組數組和變量。
typedef struct
{
double current;
unsigned int subject;
}CGPA;
typedef struct
{
char program[40];
char state[50];
char name[50];
char contact[50];
string studentid;
CGPA a;
}INFOR;
如何將它們存儲在其他變量中以供以后處理?
這是我的代碼的某些部分,但是它無法獲取正確的值並將它們從txt文件存儲到我的struct數組中:
for( int i = 0; getline(readfile, line); i++)
{
//getline(readfile,student[i].id, '\0');
//getline(readfile,student[i].a.subject, '\0');
//strcpy(student[i].subject, temporary_s);
readfile >> student[i].studentid >> student[i].program >> student[i].state >> student[i].a.current >> student[i].a.subject >> student[i].name >> student[i].contact; //This is my code cannot read my text file correctly
++line_count;
}
這是我的示例輸出: 在此處輸入圖像說明,我想刪除文件的某些行,更新文件的某些行並顯示較低或較高的CGPA,這就是為什么我需要將文本文件值恢復到數組以供以后處理的原因。
該代碼無法以正確的方式讀取我的文件,我不知道如何處理
readfile >> student[i].studentid >> student[i].program >> student[i].state >> student[i].a.current >>student[i].a.subject >> student[i].name >> student[i].contact; //This is my code cannot read my text file correct
我不知道為什么您可以將CGPA數據與其余的數據放到INFOR中時需要一個單獨的結構,但我已經離開了。 我確實將所有字符數組都更改為std :: string,因為將它們作為字符數組並沒有明顯的優勢。 我將INFOR的數組更改為std :: vector,因為將數組作為數組沒有明顯的優勢。 如果確實需要按您的要求對結構進行布局,請告訴我,因為需要更改代碼。
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct CGPA
{
double current;
unsigned int subject;
};
struct INFOR
{
std::string program;
std::string state;
std::string name;
std::string contact;
std::string studentid;
CGPA a;
};
bool testing = true;
main() {
if(testing) {
std::ofstream writeFile("file.txt");
writeFile << "1\tClass Physics\tAmerican\t3.6\t5\tMaria Garcia\t1-541-754-3010\n"
<< "2\tClass Chemical\tAustralian\t3.5\t4\tMaria Hernandez\t1-541-754-3233\n";
writeFile.close();
}
std::vector<INFOR> students;
std::ifstream readfile("file.txt");
std::string line;
while(std::getline(readfile, line))
{
std::stringstream ss(line);
INFOR student;
std::string column;
getline(ss, column, '\t'); student.studentid = column;
getline(ss, column, '\t'); student.program = column;
getline(ss, column, '\t'); student.state = column;
ss >> student.a.current;
ss >> student.a.subject;
getline(ss, column, '\t'); student.name = column;
getline(ss, column, '\t'); student.contact = column;
students.push_back(student);
}
readfile.close();
int line_count = students.size();
if(testing) {
std::cout << line_count << " lines";
}
return line_count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.