如何从文件中将名称插入2D char数组

时间:2016-04-01 13:41:14

标签: c++

我正在编程学生,我的老师告诉我将文件中的一些名字存储到2D char数组中。现在我知道字符串很简单,但我的老师限制我只使用cstring。

这是我的代码:

#include<iostream>
#include<fstream> 
#include<cstring>
int main()
{
char names[5][50];
int row=0,col=0,x=0; 
ifstream input("file.txt");

while(input.good())
{
    input.getline(names[row],50);
    row++;
    cout<<names;        
}
input.close();
return 0; 

}

它给了垃圾价值。 这是我的输入文件:

  • Aasim nadeem
  • talha arif
  • naeem tahir
  • ahmad saleem
  • saleem athar

1 个答案:

答案 0 :(得分:2)

cout<<names;似乎正在尝试打印整个2D数组,但cout不知道如何处理,因此将其视为地址并打印出来。如果您尝试打印单个名称(即out<<names[row-1];),则这些是字符指针,因此 知道如何打印它们。