2016-11-27 59 views
0

我想打開一個文本文件並將其全部讀取,同時使用C++將其內容存儲到變量和數組中。下面我有我的示例文本文件。我想將第一行存入一個整數變量,第二行寫入一個3d數組索引,最後一行寫入一個字符串數組的5個元素。我知道如何打開文件進行讀取,但我還沒有學會如何讀取某些單詞並將它們存儲爲整數或字符串類型。我不知道如何在C++中實現這一點,任何幫助,非常感謝。如何將.txt文件中的文本讀入數組?

3 
2 3 3 
4567 2939 2992 2222 0000 
+0

太多這樣的問題。在互聯網上搜索「stackoverflow C++讀取文件數組」。 –

回答

1

使用ifstream的

std::ifstream input("filename.txt"); 

爲了能夠按行讀入行:

for(std::string line; getline(input, line);) 
{ 
//do what you want for each line input here 
} 
1

閱讀所有的整數中的文本文件:

#include <fstream> 

int main() { 
    std::ifstream in; 
    in.open("input_file.txt") 
    // Fixed size array used to store the elements in the text file. 
    // Change array type according to the type of the elements you want to read from the file 
    int v[5]; 
    int element; 

    if (in.is_open()) { 
     int i = 0; 
     while (in >> element) { 
      v[i++] = element; 
     } 
    } 

    in.close(); 

    return 0; 
} 
1

試試這個:

#include <iostream> 
#include <string> 
#include <fstream> 

int main() 
{ 
    std::ifstream file("filename.txt"); // enter the name of your file here 

    int firstLine; 

    int secondLine; 
    const int X = 3; 
    const int Y = 1; 
    const int Z = 1; 
    int ***arr3D; 

    std::string myArray[5]; 
    std::string myString; 

    if (file.is_open()) 
    { 
     // store the first line into an integer variable 
     file >> firstLine; 

     // store the second line into a 3d array index 
     arr3D = new int**[X]; 
     for (int i = 0; i < X; i++) 
     { 
      arr3D[i] = new int*[Y]; 

      for (int j = 0; j < Y; j++) 
      { 
       arr3D[i][j] = new int[Z]; 

       for (int k = 0; k < Z; k++) 
       { 
        file >> secondLine; 
        arr3D[i][j][k] = secondLine; 
       } 
      } 
     } 

     // store the final line into 5 elements of a string array 
     int i = 0; 
     while (file >> myString) 
     { 
      myArray[i] = myString; 
      i++; 
     } 
    } 

    file.close(); 


    std::cout << firstLine << std::endl; 

    for (int i = 0; i < X; i++) 
    { 
     for (int j = 0; j < Y; j++) 
     { 
      for (int k = 0; k < Z; k++) 
      { 
       std::cout << arr3D[i][j][k] << std::endl; 
      } 
     } 
    } 

    for (int i = 0; i < 5; i++) 
    { 
     std::cout << myArray[i] << std::endl; 
    } 

    return 0; 
} 
+0

我拒絕了[你的一個編輯](http://stackoverflow.com/review/suggested-edits/14444577),最近你也遭到了類似的拒絕。請不要在問題中編輯其他人的代碼!你永遠無法知道你的具體編輯是否意外地解決了提問者的原始問題。如果有的話,堅持格式化和語法和標籤。 (我在編輯的拒絕原因中寫了很多,但我不確定你是否讀過它。)謝謝。 –

+0

非常感謝。 –