Noobie警报。呃。我在使用<stdio.h>或<fstream>完成一些基本的文件I/O工作时遇到了一些真正的问题。它们看起来都很笨拙,使用起来也不直观。我的意思是,为什么C++不能提供一种方法来获取指向文件中第一个字符的char*指针呢?这就是我一直想要的。
我正在做Project Euler Question 13,需要处理50位数字。我将150个数字存储在文件13.txt中,并尝试创建一个150x50数组,这样我就可以直接处理每个数字的数字。但我有很多麻烦。我尝试过使用C++ <fstream>库和最近直接使用的<stdio.h>来完成这项工作,但一定有什么东西不适合我。这是我所拥有的;
#include <iostream>
#include <stdio.h>
int main() {
const unsigned N = 100;
const unsigned D = 50;
unsigned short nums[N][D];
FILE* f = fopen("13.txt", "r");
//error-checking for NULL return
unsigned short *d_ptr = &nums[0][0];
int c = 0;
while ((c = fgetc(f)) != EOF) {
if (c == '\n' || c == '\t' || c == ' ') {
continue;
}
*d_ptr = (short)(c-0x30);
++d_ptr;
}
fclose(f);
//do stuff
return 0;
}有人能给点建议吗?也许是他们喜欢的I/O库上的C++人员?
发布于 2013-01-26 08:51:04
这里有一个很好的有效的解决方案(但不适用于管道):
std::vector<char> content;
FILE* f = fopen("13.txt", "r");
// error-checking goes here
fseek(f, 0, SEEK_END);
content.resize(ftell(f));
fseek(f, 0, SEEK_BEGIN);
fread(&content[0], 1, content.size(), f);
fclose(f);这是另一个:
std::vector<char> content;
struct stat fileinfo;
stat("13.txt", &fileinfo);
// error-checking goes here
content.resize(fileinfo.st_size);
FILE* f = fopen("13.txt", "r");
// error-checking goes here
fread(&content[0], 1, content.size(), f);
// error-checking goes here
fclose(f);发布于 2013-01-26 08:26:28
我会使用fstream。您遇到的一个问题是,您显然不能将文件中的数字与C++的任何本机数字类型(double、long long等)相匹配。
不过,将它们读入字符串非常简单:
std::fstream in("13.txt");
std::vector<std::string> numbers((std::istream_iterator<std::string>(in)),
std::istream_iterator<std::string>());这将把每个数字读入一个字符串,所以第一行上的数字将是numbers[0],第二行是numbers[1],依此类推。
如果你真的想用C语言完成这项工作,它仍然可以比上面的方法容易得多:
char *dupe(char const *in) {
char *ret;
if (NULL != (ret=malloc(strlen(in)+1))
strcpy(ret, in);
return ret;
}
// read the data:
char buffer[256];
char *strings[256];
size_t pos = 0;
while (fgets(buffer, sizeof(buffer), stdin)
strings[pos++] = dupe(buffer);发布于 2013-01-26 08:37:19
与其从文件中读取150位数字,为什么不直接从字符常量中读取它们呢?
你可以这样开始你的代码:
static const char numbers[] =
"37107287533902102798797998220837590246510135740250"
"46376937677490009712648124896970078050417018260538"...在最后一行加上分号。
https://stackoverflow.com/questions/14532399
复制相似问题