0

My aim is to fill an array of strings with each word in a dictionary file (/usr/share/dict/words). I'm able to iterate through each line in the file using an ifstream to determine the number of elements I will need in my string array. That being said, I am unclear how to instantiate and then fill my array of strings? I believe there is some casting I am missing, but nevertheless my code is below. Note the error occurs on line 40:

error: cannot convert 'std::string' to 'char*' for argument '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);
    }   
}
1
  • 1
    Just use assignment: dictArray[i] = line; Commented Nov 27, 2014 at 0:55

1 Answer 1

2

You can simply use an assignment instead of strncpy:

dictArray[i] = line;

Edit: After the while loop, you probably want to reset the stream position:

dictionary.seekg(0);
Sign up to request clarification or add additional context in comments.

6 Comments

Are you sure the use of getline is correct? (i.e. man getline is not the same as dictionary.getline()
I do not know if the OP wanted to use getline or not and if it is correct in his context, the compilation error that he is having is related to using strncpy.
As for the problems with correctness of the program, getline actually looks fine in this context. There might be an issue with the OP not resetting position in the stream after counting the number of newlines.
OP Here. What is the significance of resetting the stream position with dictionary.seekg(0)?
Also, I just replaced the strncpy line with dictArray[i] = line; and reset the stream position after the while loop, but when I use the gdb and step to this line, the value in the string variable "line" is "" every time so my dictArray elements are all filled with "". What would cause my getline to fill line with empty strings instead of words from the variable dictionary?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.