簡體   English   中英

從文件讀取到字符串

[英]Read from file to string

好吧,首先,我知道我正在使用stdio.h通過C ++讀取文件,但是請忽略它,我需要這樣做。

我有這個文件:

5
peter
josh
edward
mary
lois

我需要閱讀第一個數字(簡單):

int np;

FILE *myfile = fopen("myfile.txt", "r");
fscanf(myfile, "%d", &np);

然后,我需要閱讀以下np名稱:

string people[np];
for (int i = 0; i < np; i++) {
  fscanf(myfile, "%s", &people[i]);
  fscanf(myfile, "\n");
}

但是,我得到了SEGFAULT。 當我使用gdb時,我得到了:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b6e603 in std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /usr/lib/libstdc++.so.6

我認為這是因為我有一個字符串數組,而且我正在讀取char *,如何使用stdio.h文件讀取命令將行另存為字符串?

string people[np];
fscanf(myfile, "%s", &people[i]);

那里有兩個問題。 (問題多於這些,但我們只關注這些。)

1) C ++不支持可變長度數組。 如果您使用其他某種編程語言(例如帶有擴展名的g ++)進行編程,請隨時使用它們。 但是,如果您需要編寫C ++程序,則需要做其他事情。 嘗試例如

std::vector<std::string> people(np);

2) fscanf需要一個char* ,而不是一個string*這實際上是導致您的段錯誤的錯誤,實際上沒有解決此問題的好方法。 以下內容雖然仍然存在問題,但可能足以滿足您的需求:

char buffer[256];
fscanf(myfile, "%s", buffer);
people[i] = buffer;

編輯 :幾個月后,當我閱讀我的答案時,我需要添加C ++慣用的方式來做到這一點:

int np;
std::cin >> np;

// copy all remaining names
std::vector<std::string> people;
std::copy((std::istream_iterator<std::string>(std::cin)),
           std::istream_iterator<std::string>(),
           std::back_inserter(people));


// Or, (c++11 only) copy exactly "np" names
std::vector<std::string> people;
std::copy_n((std::istream_iterator<std::string>(std::cin)),
           np,
           std::back_inserter(people));

在您的程序中,您使用的是字符串類的地址,而不是字符緩沖區的地址。 fscanf需要將字符串復制到的字符緩沖區(字符數組)。 您需要將字符串讀取到臨時緩沖區中,然后進行分配。

char tempBuffer[1024];
string people[np];

for (int i = 0; i < np; i++) 
{      
  fscanf(myfile, "%s", tempBuffer);
  fscanf(myfile, "\n");
  people[i] = tempBuffer;
}    

字符串類的=運算符可以使用字符緩沖區,然后將其復制。

可能有一種直接將其分配給字符串的方法,但我想不起來一種可以立即使用的方法。

首先將內容讀取為c字符串,然后(之后)從中構造std:strings。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM