0

努比警报。啊。我在<stdio.h>使用<fstream>. 它们看起来都很笨重且使用起来不直观。我的意思是,为什么 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;
}

有人可以提供一些建议吗?也许是 C++ 人,他们更喜欢哪个 I/O 库?

4

3 回答 3

1

我会使用 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-26T00:26:27.863 回答
1

这是一个很好的有效解决方案(但不适用于管道):

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-26T00:51:04.407 回答
0

与其从文件中读取 100 个 50 位数字,为什么不直接从字符常量中读取它们呢?

你可以开始你的代码:

static const char numbers[] = 
 "37107287533902102798797998220837590246510135740250"
 "46376937677490009712648124896970078050417018260538"...

最后一行有一个分号。

于 2013-01-26T00:37:18.973 回答