2013-09-24 117 views
0

我需要从文件读取并存储在不同数组中的代码!从文件中读取并存储在不同的数组中

为例如:

保罗23 54

约翰32 56

我的要求如下:我需要存储在字符串数组paul,john,并且在一个整数数组23,32;和另一个int阵列中的54,56类似。

我从文件读取输入并打印它,但我无法保存在3个不同的阵列中。

int main() 
{ 
    string name; 
    int score; 
    ifstream inFile ; 

    inFile.open("try.txt"); 
    while(getline(inFile,name)) 
    { 
     cout<<name<<endl; 
    } 
    inFile.close();  

} 

那么好心建议我要这个干什么一些逻辑,我会非常感谢...!

+0

你丢失的数据结构,如;数组,Arraylist,链表和向量。您需要数据结构来保存输入数据并进行存储。 – Juniar

回答

0

我假设你是编程新手?还是新的C++?所以我提供了示例代码来帮助您开始。 :)

#include <string>; 
#include <iostream> 
#include <vector> 
using namespace std; 

int main() { 
    vector<string> name; 
    vector<int> veca, vecb; 
    string n; 
    int a, b; 

    ifstream fin("try.txt"); 
    while (fin >> n >> a >> b) { 
     name.push_back(n); 
     veca.push_back(a); 
     vecb.push_back(b); 
     cout << n << ' ' << a << ' ' << b << endl; 
    } 
    fin.close() 

    return 0; 
} 
0

你可以试试下面的代码:

#include <string> 
#include <vector> 

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::string fileToRead = "file.log"; 
    std::vector<int> column2, column3; 
    std::vector<std::string> names; 
    int number1, number2; 
    std::string strName; 

    std::fstream fileStream(fileToRead, std::ios::in); 
    while (fileStream>> strName >> number1 >> number2) 
    { 
     names.push_back(strName); 
     column2.push_back(number1); 
     column3.push_back(number2); 
     std::cout << "Value1=" << strName 
      << "; Value2=" << number1 
      << "; value2=" << number2 
      << std::endl; 
    } 
    fileStream.close(); 
    return 0; 
} 

的想法是在文件中的第一列中读取到一个字符串(则strName),然后把它推到一个向量(地名)。同样,第二列和第三列先读入number1和number2,然后分别推入名为column1和column2的矢量中。

运行它,会得到以下结果:

Value1=paul; Value2=23; value2=54 
Value1=john; Value2=32; value2=56 
+0

谢谢我会尽力! –

相关问题