I'm trying to make a program which gives me all the words that have a certain number of letters, it gives me the error: "invalid conversion from 'char' to 'const char*' [-fpermissive]". I have googled and searched around for a solution and have read the references but I don't know what to change.
#include <iostream>
#include <fstream>
#include <math.h>
#include <string.h>
usingnamespace std;
int main()
{
ifstream f("words.txt");
int nr_words;
f >> nr_words; //first line of the txt file is the nr of words
char v[nr_words];
for(int i=1; i<nr_words; i++)
{
f >> v[i];
cout<<v[i]<<" ";
}
cout<<endl;
cout<<endl;
int nr_letters;
cout<<"number of letters the word has: ";
cin>>nr_letters;
for(int i=1; i<nr_words; i++)
{
if(strlen(v[i])==nr_letters)
cout<<v[i];
}
return 0;
}
char v[nr_words];
This creates an array of char. Each char can hold ONE letter. Yet you seem to be trying to store entire words in them. This makes no sense.
At line 14 you define an array of single 'char'-types. but in line 19 you're probably try reading a whole c-string word into a single 'char' storage space!
You could expand your 'char' array at line 14 to a 2-dimensional type: char v[nr_words][32];
But be aware that using raw arrays for is error prone. c++ offers better alternatives. Here a suggestion by using std::vector and std::string objects:
also, @holyheck, is there a reason you're trying to work with C-style strings? You're using C++ input/output operations, C++ file operations, and then suddenly C character arrays and related functions.
Many times when including with the angle brackets but providing a .h file, like #include <string.h> will bring in a file from the C standard lib (unless you have specific custom changes to your project's include directories). This can be made clearer by putting a "c" in front and removing the ".h", as in #include <cstring> or #include <cmath> . Readers now know you're specifically bringing in something from the C libs.
I'd try to avoid including C stuff altogether and use as many C++ libs as possible
#include <iostream>
#include <fstream>
#include <string> // C++ std::string
usingnamespace std;
int main()
{
string file_name("words.txt");
// Just slightly clearer to name your variable to show it's not just any stream but an input file stream
ifstream ifs(file_name);
if (!ifs)
{
cout << "Unable to open \""<<file_name<<"\". Please check it exists and not in use.\n";
return -1;
}
int nr_letters;
cout << "Letters in word? ";
cin >> nr_letters;
int nr_words;
ifs >> nr_words; // It's cool that your file has this at the top, but it's not really needed
string word;
while (ifs >> word)
{
// Do stuff if word.size() is correct...
}
return 0;
}