【问题标题】:How to read words from text file and store into 2 dimensional array如何从文本文件中读取单词并存储到二维数组中
【发布时间】:2017-04-02 12:49:39
【问题描述】:
#include <iostream>
using namespace std;

int main(){

string Firstname,Surname;

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

return 0;

如果用户只有名字,我希望命令能够正常工作,通常如果用户不输入姓氏,它会不断地一次又一次地询问他们.....

【问题讨论】:

  • stackoverflow.com 不是家庭作业网站。向我们展示您的努力或代码。
  • 请至少添加您自己的尝试。 1.你想从文件中读取:谷歌怎么做! 2. 你想将一些东西存储到一个二维数组中:谷歌它! 3. 合并两个概念。如果出现任何错误,请再次询问。
  • 伙计们,这是我阅读文件的代码@MohammadTayyab
  • 您的预期输出是什么? @Puneet
  • 我希望它存储在二维数组中,然后在一行中输出它的名字和第二个名字@MohammadTayyab

标签: c++ arrays string


【解决方案1】:

我已经注释了我的代码并编写了一个代码来从文件中读取名称并根据需要将它们存储到二维字符串数组中。

文本文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多