我的目标是用字典文件(/ usr / share / dict / words)中的每个单词填充一个字符串数组。我能够使用ifstream迭代文件中的每一行,以确定我在字符串数组中需要的元素数量。话虽这么说,我不清楚如何实例化然后填充我的字符串数组?我相信有一些我失踪的演员,但不过我的代码在下面。请注意,错误发生在第40行:
错误:无法转换' std :: string'到#char;'争论' 1' to' char * strncpy(char *,const char *,size_t)'
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fstream>
#include <sstream>
using namespace std;
const int MAX_WORD_LENGTH = 40;
int main(int argc, char *argv[]){
char c;
int numLines = 0;
string line;
ifstream dictionary("/usr/share/dict/words");
if (dictionary==0){ //exits program if dictionary file wasn't opened correctly
fprintf(stderr, "failed to open /usr/share/dict/words\n");
exit(1);
}
while (dictionary.get(c)){ //counts number of lines and stores them in int numLines
if (c=='\n'){
numLines++;
}
}
//char *dictArray[numLines][MAX_WORD_LENGTH];
string dictArray[numLines];
printf("%d\n", numLines); //debugging
for(int i = 0; i < numLines; i++){ //loop to fill string array with each word in dictionary file
getline(dictionary, line);
strncpy(dictArray[i], line.c_str(), 40);
}
}
答案 0 :(得分:2)
您只需使用赋值而不是strncpy:
dictArray[i] = line;
编辑:
在while
循环之后,您可能想要重置流位置:
dictionary.seekg(0);