如何从文本文件中读取单词并存储到二维数组中

时间:2017-04-02 12:49:40

标签: c++ arrays string

#include <iostream>
using namespace std;

int main(){

string Firstname,Surname;

cout << "Full name:" <<endl;
cin >> Firstname >> Surname; 

return 0;

如果用户只有名字,我希望这些命令有效,通常如果用户没有输入姓氏,它会不断地一次又一次地询问他们......

1 个答案:

答案 0 :(得分:0)

我已经对我的代码进行了评论,并制作了一个代码来从文件中读取名称,并根据需要将它们存储到2D字符串数组中。

文字档案

James
Will
Bruce 
Wayne
Harry    
Potter

<强>代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str;
    int count=0;
    ifstream in("File.txt");
    while (!in.eof())
    {
        getline(in, str);
        count++; //counting names
    }
    in.close();
    count = count / 2; //dividing count by 2
    //SYNTAX FOR 2D ARRAY
    string **nameArray = new string*[count]; //making array of count/2
    for (int i = 0; i < count; i++)
        nameArray[i] = new string[2]; //evvery index have 2 column one for first name and second for last name
    //2D array done
    in.open("File.txt");
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
                   // getline(in,nameArray[i][j]; // if you want to read sentence.not a single word.
            //in >> nameArray[i][j]; //if you want to read name or a single word.
        }
    }
    in.close();
    for (int i = 0; i < count; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cout<<nameArray[i][j]<<" "; //Printing [i,j] with first and second name
        }
        cout << endl;
    }
    for (int i = 0; i < count; i++)
        delete[] nameArray[i];
    delete[] nameArray;
    system("pause");
    return 0;
}

<强>输出

James Will
Bruce Wayne
Harry Potter