c++ - 如何正确写入多维字符数组未知数量的值但固定数量的字符

标签 c++ variables multidimensional-array

<分区>

我厌倦了解决为什么我的 ch[0] 的值是“Thomas EdisonÇ@”,而它应该是“Thomas Edison”

int main(){
using namespace std;
ifstream in("U2.txt");
int n;
in>>n; //n=rows, so in every line there will be "name surname", time, money

char ch[n][21]; //I'm trying to get Name+Surname which must be 20 char long
in.read(ch[0], 20);
cout << ch[0]; //but getting Thomas EdisonÇ@
return 0;}

它适用于一维 ch[21],但会有很多值,所以我想使用 ch[n][21]

欢迎任何其他开箱即用的解决方案,我累了

最佳答案

你忘记了 C 字符串需要以 nul 结尾

in.read(ch[0], 20);
ch[0][20] = '\0'; // add the nul terminator
cout << ch[0];    // now correct output

关于c++ - 如何正确写入多维字符数组未知数量的值但固定数量的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54170517/

相关文章:

python获取文件名并在另一个脚本中打开

variables - 批处理 : FOR/R doesn't work with a variable in the path

javascript - 从 .PHP 文件获取变量并在 .JS 文件中回显它

c - 增加在数组指针数组中实现的数组的最后一行?

php - 多维数组上的 json_encode() - 带有字符串键

c++ - 使用 "Error: expression must have a pointer type"关键字时为 "this"

c++ - 保持模块独立,同时仍然相互使用

c++ - 使用 ppl.h 查找最大值

javascript - 将属性插入多维数组

c++ - 基于boost::threads的队列算法