C++ 如何从文本文件中读取单词并存储到二维数组中
如果用户只有名字,我希望这些命令能起作用,通常情况下,如果用户没有输入姓氏,它会不断地反复询问 我已经对我的代码进行了注释,并编写了一个代码,用于从文件中读取名称,并根据需要将其存储到二维字符串数组中 文本文件 代码:C++ 如何从文本文件中读取单词并存储到二维数组中,c++,arrays,string,C++,Arrays,String,如果用户只有名字,我希望这些命令能起作用,通常情况下,如果用户没有输入姓氏,它会不断地反复询问 我已经对我的代码进行了注释,并编写了一个代码,用于从文件中读取名称,并根据需要将其存储到二维字符串数组中 文本文件 代码: stackoverflow.com不是家庭作业网站。向我们展示您的努力或代码。请至少添加您自己的尝试。1.你想从一个文件中读取:谷歌怎么做!2.你想将一些东西存储到二维数组中:用谷歌搜索它!3.合并这两个概念。如果出现任何错误,请再次询问。伙计们,这是我读取文件@Mohammad
stackoverflow.com不是家庭作业网站。向我们展示您的努力或代码。请至少添加您自己的尝试。1.你想从一个文件中读取:谷歌怎么做!2.你想将一些东西存储到二维数组中:用谷歌搜索它!3.合并这两个概念。如果出现任何错误,请再次询问。伙计们,这是我读取文件@MohammadTayyab的代码。您的预期输出是什么@PuneetI希望将其存储在二维数组中,然后在一行@MohammadTayyab中输出其第一个名称和第二个名称
#include <iostream>
using namespace std;
int main(){
string Firstname,Surname;
cout << "Full name:" <<endl;
cin >> Firstname >> Surname;
return 0;
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