现在我已经可以读取文件内的数据储存到 int array 里。但是我想要转化成 string ,要怎么做才可以啊。 代码如下。
FILE *fp; char *fileName; int num[31000]; int i = 0; //read data file fileName = malloc(sizeof(char)*0); printf("Enter data file name: \n"); scanf("%s", fileName); fp = fopen(fileName, "r"); if(fp != NULL) { while(!feof(fp)) { i++; fscanf(fp, "%d", &num[i]); } } else { printf("cannot open file\n"); }
1 Cbdy 2017-03-10 07:00:49 +08:00 via Android 算一下 int 多大,然后在堆里直接开一个二维 char 数组得了 |
2 hocking 2017-03-10 07:33:51 +08:00 via iPhone 如果你的数据本来就是字符,可以直接以文本的形式读 |
![]() | 3 binux 2017-03-10 07:39:12 +08:00 我怎么看不懂 LZ 在说什么,什么叫「 int array 转化成 string array 」,你想怎么「转化」? |
![]() | 4 cs202 2017-03-10 07:43:23 +08:00 简单地搜索了一下,找到了这个: http://stackoverflow.com/questions/5223066/converting-int-to-string-in-c string int_array_to_string(int int_array[], int size_of_array) { string returnstring = ""; for (int temp = 0; temp < size_of_array; temp++) returnstring += itoa(int_array[temp]); return returnstring; } OR string int_array_to_string(int int_array[], int size_of_array) { ostringstream oss(""); for (int temp = 0; temp < size_of_array; temp++) oss << int_array[temp]; return oss.str(); } |
5 wevsty 2017-03-10 08:24:14 +08:00 4 楼正解 C++推荐使用 strstream 来解决问题。 |
6 debiann 2017-03-10 08:34:54 +08:00 via iPhone 有现成的 itoa atoi |
![]() | 7 zhidian 2017-03-10 09:02:23 +08:00 用 std::copy 啊,核心代码: std::ostringstream oss; std::copy( intArray, intArray+length, std::ostream_iterator<int>(oss, ", ") ); 代码: http://coliru.stacked-crooked.com/a/acdd0bb927e1d8f8 |
![]() | 8 gary907478 OP 补充一下,这个用的是 c 语言,转化问题解决了,但是现在是个新问题就是数据里边有 0 开头的整数读取后 0 就消失了,不知道为什么。例如文档里是 000123 ,读取后打印出来就变成了 123. |
![]() | 9 gary907478 OP @cs202 感谢回复,可是我用的不是 C++而是 C 语言。 |
![]() | 10 gary907478 OP @zhidian 感谢回复,我是用 C 的 |
![]() | 11 zhidian 2017-03-10 09:24:08 +08:00 @gary907478 好吧……我想你需要的是 2 楼的答案。 |
![]() | 12 gary907478 OP @hocking 数据全都是数字 2381293 3281903 这样的,每个数据中间有空格分割。 |