[英]fscanf not reading strings into array
為什么這個主要印刷品什么都沒有? 它應該打印文件中的第一個單詞。
int main(int argc, char *argv[])
{
FILE *file = fopen(argv[1], "r");
int n = atoi(argv[2]);
char **words = new char*[n];
for(int i = 0; i < n; i++)
{
fscanf(file, "%s ", words[i]);
}
cout << words[0] << endl;
}
words[i]
是指向隨機存儲器位置的指針。 確保使其指向分配的內存。
//Now words[i] points to the 1000 bytes allocated with the new keyword
words[i] = new char[1000];
//fscan will write the input to those bytes
fscanf(file, "%s ", words[i]);
char **words = new char*[n];
將分配一個緩沖區來保存n個指向char的指針, words
只是指向指針數組的指針。 您需要為words[i]
(指向的指針)分配足夠的內存以容納字符串:
for (i=0; i < n; ++i ) {
words[i] = new char[your_max_string_len];
}
(可選)您可以使用GNU的 getline
擴展 (如果使用gcc)來執行所需的操作:
size_t len = 0;
ssize_t read;
read = getline(&words[i], &len, stdin);
...
free(words[i]);
實際上,此功能沒有魔術,它只是在后台進行內存分配以保存您的內存,而您有責任釋放它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.