Initializer but incomplete type? - c++

The following code gives me 2 errors when i compile
#include <iostream>
#include <fstream>
#include <cstring>
#include "Translator.h"
using namespace std;
void Dictionary::translate(char out_s[], const char s[])
{
int i;
char englishWord[MAX_NUM_WORDS][MAX_WORD_LEN];
for (i=0;i < numEntries; i++)
{
if (strcmp(englishWord[i], s)==0)
break;
}
if (i<numEntries)
strcpy(out_s,elvishWord[i]);
}
char Translator::toElvish(const char elvish_line[],const char english_line[])
{
int j=0;
char temp_eng_words[2000][50];
//char temp_elv_words[2000][50]; NOT SURE IF I NEED THIS
std::string str = english_line;
std:: istringstream stm(str);
string word;
while( stm >> word) // read white-space delimited tokens one by one
{
int k=0;
strcpy (temp_eng_words[k],word.c_str());
k++;
}
for (int i=0; i<2000;i++) // ERROR: out_s was not declared in this scope
{
Dictionary::translate (out_s,temp_eng_words[i]); // ERROR RELATES TO THIS LINE
}
}
Translator::Translator(const char dictFileName[]) : dict(dictFileName)
{
char englishWord[2000][50];
char temp_eng_word[50];
char temp_elv_word[50];
char elvishWord[2000][50];
int num_entries;
fstream str;
str.open(dictFileName, ios::in);
int i;
while (!str.fail())
{
for (i=0; i< 2000; i++)
{
str>> temp_eng_word;
str>> temp_elv_word;
strcpy(englishWord[i],temp_eng_word);
strcpy(elvishWord[i],temp_elv_word);
}
num_entries = i;
}
str.close();
}
}
The first one is at std::string istringstream stm(str); where it says it the variable has an initializer but incomplete type. If I put in std::string istringstream stm(str); it says expected initializer before stm andstm was not declared in the scope.
It also says out_s was not declared in this scope at Dictionary::translate (out_s,temp_eng_words[i]);. I don't see why one parameter is recognisied and one is not?
Thanks in advance.

You have to include header file:
#include <sstream>
#include <string>
when you want to use stringstream and string.
Meanwhile:
Dictionary::translate (out_s,temp_eng_words[i]);
If out_s is not a member of the class, you seems forgot to define out_s before using it inside toElvish.
Meanwhile:
while( stm >> word) // read white-space delimited tokens one by one
{
int k=0; //^^Why do you initialize k everytime you read a word?
strcpy (temp_eng_words[k],word.c_str());
k++;
}

You just need to include sstream

Your translator would be much simpler if you used std::map.
#include <map>
#include <string>
// map[english word] returns the elvish word.
typedef std::map<std::string, std::string> Dictionary;
// Define the dictionary
Dictionary english_to_elvish_dictionary;
std::string To_Elvish(const std::string& english_word)
{
Dictionary::iterator iter;
std::string elvish_word;
iter = english_to_elvish_dictionary.find(english_word);
if (iter != english_to_elvish_dictionary.end())
{
// English word is in dictionary, return the elvish equivalent.
elvish_word = *iter;
}
return elvish_word;
}
The above code fragment replaces most of your code and reduces your issues with arrays of arrays of C-strings. Less code == less problems.
To see a list of issues your having, search StackOverflow for "[c++] elvish english".

Related

i have an assignment that works in compiler but does not work properly in assignment website

I have a homework that requires me to do operations on a string, I used an iterator in the second function to find the last index of a letter in the string and first index of it to find the distance between them.
here is my code, focus on int textProcessing(const string &inputString, char letter); function:
#include <iostream>
#include <fstream>
#include <string>
#include<algorithm>
#include <iomanip>
#include <iterator>
using namespace std;
void textProcessing(string &inputString);
int textProcessing(const string &inputString, char letter);
void textProcessing(string &inputString, char orgChar, char newChar);
int main() {
ofstream out("text.txt");
out<<"the earth is a very small stage in a vast cosmic arena";
out.close();
unsigned short operation;
cin >> operation;
string sentence;
fstream inputstream;
inputstream.open("text.txt");
while (!inputstream.eof()) {
getline(inputstream, sentence);
if (sentence.length() > 0) {
// Your code starts here
if (operation==0){
textProcessing(sentence);
}
else if(operation==1){
char rletter;
cin>>rletter;
if(isupper(rletter)){
cout<<"Invalid";
}
else {
int ans = textProcessing(sentence, rletter);
cout << ans;
}
}
else if(operation==2){
char orignal;
char newl;
cin>>orignal>>newl;
textProcessing(sentence,orignal,newl);
}
else{
cout<<"Invalid";
}
// Your code ends here
}
}
return 0;
}
void textProcessing(string &inputString){
inputString.erase(remove(inputString.begin(),inputString.end(),'a'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'o'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'u'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'w'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'y'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'i'),inputString.end());
inputString.erase(remove(inputString.begin(),inputString.end(),'e'),inputString.end());
cout<<inputString;
};
int textProcessing(const string &inputString, char letter){
int count=0;
auto it=find(inputString.rbegin(),inputString.rend(),letter);
int last_index =distance(inputString.begin(), (it + 1).base());
int first=inputString.find(letter);
int distance=(last_index-first);
return distance;
};
void textProcessing(string &inputString, char orgChar, char newChar){
if((isupper(orgChar))/*||(isupper(newChar))*/){
cout<<"Invalid";
}
else {
for (int i = 0; i <= inputString.length(); i++) {
if (inputString[i] == orgChar) {
inputString[i] = newChar;
}
}
cout<<inputString;
}
}
and here is the error from assignment website:
Your program displayed : student.cpp: In function ‘int textProcessing(const string&, char)’: student.cpp:79:10: error: ‘it’ does not name a type
System Message: ERROR/3 (<string>, line 3)
Unexpected indentation.
auto it=find(inputString.rbegin(),inputString.rend(),letter);
^
System Message: WARNING/2 (<string>, line 5)
Block quote ends without a blank line; unexpected unindent.
student.cpp:80:52: error: ‘it’ was not declared in this scope
int last_index =distance(inputString.begin(), (it + 1).base());
^
The problem ‘it’ does not name a type is most surely caused by the use of auto in a Pre-C++11 standard compiler.
Make sure you're using C++11 or higher as auto is a C++11 feature.
There may be other problems with your code but the question is about the compiler error ‘it’ does not name a type.
There are many other online websites to compile and run your program one of which is this.

How to put an element of a string to a vector?

I want to put specific elements of a string to a vector<string>.
To give you a better explanation of what i intend to do:
string str;
vector<string> in;
cin >> str; // input: abc
for(int i = 0;i < str.length();i++) {
in.push_back(&str[i]);
}
now i want the first element of vector<string> in to be "a" (in[0] = "a"), the second to be b etc.. i want to use strings for this. Is it possible to do it because when i print the vector it gives me that first it has abc then bc and in the end only c?
std::string has a constructor that takes a integral count and a single char to instantiate a string with n elements of the same value. You can use this and the fact that std::strings is much like a container of char:
for (auto c : str)
in.emplace_back(1ul, c);
Alternatively, you can store single char in the vector instead of std::string:
std::vector<char> in(str.begin(), str.end());
Either use std::vector<char> or use substr.
Example 1:
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::vector<char> in;
std::cin >> str; // input: abc
for (std::string::size_type i = 0; i < str.length(); i++) {
in.push_back(str[i]);
}
}
Or a simpler variant:
int main()
{
std::string str;
std::cin >> str; // input: abc
std::vector<char> in(str.begin(), str.end());
}
Example 2:
#include <string>
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::vector<std::string> in;
std::cin >> str; // input: abc
for (std::string::size_type i = 0; i < str.length(); i++) {
in.push_back(str.substr(i, 1));
}
}

C++ basic syntax errors

I am getting errors with the following code and don't know where I am going wrong.
#include <iostream>
#include <fstream>
#include <cstring>
#include "Translator.h"
using namespace std;
int main (void)
{
char Dictionary::translate (char out_s[], const char s[])
{
int i;
for (i=0;i < numEntries; i++)
{
if (strcmp(englishWord[i], s)==0)
break;
}
if (i<numEntries)
strcpy(out_s,elvishWord[i]);
}
char Translator::toElvish(char elvish_line[],const char english_line[])
{
int j=0;
char temp_eng_words[2000][50];
//char temp_elv_words[2000][50]; NOT SURE IF I NEED THIS
std::string str = english_line;
std::istringstream stm(str);
string word;
while( stm >> word) // read white-space delimited tokens one by one
{
int k=0;
strcpy (temp_eng_words[k],word.c_str());
k++;
}
for (int i=0; i<2000;i++) // ERROR: out_s was not declared in this scope
{
Dictionary::translate (out_s,temp_eng_words[i]); // ERROR RELATES TO THIS LINE
}
}
Translator::Translator(const char dictFileName[]) : dict(dictFileName)
{
char englishWord[2000][50];
char temp_eng_word[50];
char temp_elv_word[50];
char elvishWord[2000][50];
int num_entries;
fstream str;
str.open(dictFileName, ios::in);
int i;
while (!str.fail())
{
for (i=0; i< 2000; i++)
{
str>> temp_eng_word;
str>> temp_elv_word;
strcpy(englishWord[i],temp_eng_word);
strcpy(elvishWord[i],temp_elv_word);
}
num_entries = i;
}
str.close();
}
}}
The first error I get is around
char Dictionary::translate (char out_s[], const char s[])
{
int i;
where it says "A function definition is not allowed before a '{' token. The second error I get is at the that there is an expected '}' at the end of input, but no matter how many i put in or leave out it still gives the same error message.
And ideas??
You're defining all the functions inside main(). Move them all before main().
You shouldn't define a function right within another function.
Function definitions come after each other.
It's not allowed to declare inner functions in C++.
Move your functions to a distinct scope, without nesting into main.

passing vector<char> to a pointer char*

how do I pass a char vector to a char*? I know this problem could easily be solved with a predefined char[] array with a SIZE const, but I want the flexibility of a vector because there will be no predefined size.
using namespace std;
//prototype
void getnumberofwords(char*);
int main() {
//declare the input vector
vector<char> input;
/*here I collect the input from user into the vector, but I am omitting the code here for sake of brevity...*/
getnumberofwords(input);
//here is where an ERROR shows up: there is no suitable conversion from std::vector to char*
return 0;
}
void getnumberofwords(char *str){
int numwords=0;
int lengthofstring = (int)str.size();
//this ERROR says the expression must have a case
//step through characters until null
for (int index=0; index < lengthofstring; index++){
if ( *(str+index) == '\0') {
numwords++;
}
}
}
You can use data() member to get the pointer to the underlying array:
getnumberofwords(input.data());
The most obvious is to pass &your_vector[0]. Be sure to add a NUL to the end of your vector first though.
Alternatively, use std::string instead of std::vector<char>, in which case you can get a NUL-terminated string with the c_str member function.
Edit: I have to wonder, however, why getnmberofwords would be written to accept a char * unless it's some old C code that you just can't get away from using.
Given a typical definition of "word" counting some words that start out in a string can be done something like this:
std::istringstream buffer(your_string);
size_t num_words = std::distance(std::istream_iterator<std::string>(buffer),
std::istream_iterator<std::string>());
You should pass the reference of the vector to the function getnumberofwords.
void getnumberofwords(vector<char>& str){
int numwords=0;
int lengthofstring = str.size();
for (int index=0; index < lengthofstring; index++){
if ( str[index] == '\0') {
numwords++;
}
}
}
There is no method for converting the type from vector to pointer.
here's what I ended up doing which worked:
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
using namespace std;
//prototype
void getnumberofwords(char*);
void getavgnumofletters(char*, int);
int main() {
const int SIZE=50;
char str[SIZE];
cout<<"Enter a string:";
cin.getline(str, SIZE);
getnumberofwords(str);
return 0;
}
void getnumberofwords(char *str){
int numwords=0;
int lengthstring=strlen(str);
//step through characters until null
for (int index=0; index < lengthstring; index++){
if (str[index] ==' ') {
numwords++;
}else{
continue;
}
}
numwords+=1;
cout<<"There are "<<numwords<<" in that sentence "<<endl;
getavgnumofletters(str, numwords);
}
void getavgnumofletters(char *str, int numwords) {
int numofletters=0;
double avgnumofletters;
int lengthstring=strlen(str);
//step through characters until null
for (int index=0; index < lengthstring; index++){
if (str[index] != ' ') {
numofletters++;
}else{
continue;
}
}
avgnumofletters = (double)numofletters/numwords;
cout<<"The average number of letters per word is "<<setprecision(1)<<fixed<<avgnumofletters<<endl;
}
/*

Using the fstream getline() function inside a class

I'm trying to load lines of a text file containing dictionary words into an array object. I want an array to hold all the words that start with "a", another one for "b" ... for all the letters in the alphabet.
Here's the class I wrote for the array object.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class ArrayObj
{
private:
string *list;
int size;
public:
~ArrayObj(){ delete list;}
void loadArray(string fileName, string letter)
{
ifstream myFile;
string str = "";
myFile.open(fileName);
size = 0;
while(!myFile.eof())
{
myFile.getline(str, 100);
if (str.at(0) == letter.at(0))
size++;
}
size -= 1;
list = new string[size];
int i = 0;
while(!myFile.eof())
{
myFile.getline(str, 100);
if(str.at(0) == letter.at(0))
{
list[i] = str;
i++;
}
}
myFile.close();
}
};
I'm getting an error saying:
2 IntelliSense: no instance of overloaded function "std::basic_ifstream<_Elem, _Traits>::getline [with _Elem=char, _Traits=std::char_traits<char>]" matches the argument list d:\champlain\spring 2012\algorithms and data structures\weeks 8-10\map2\arrayobj.h 39
I guess it's requiring me to overload the getline function, but I'm not quite certain how to go about or why it's necessary.
Any advice?
the function for streams that deals with std::string is not a member function of istream but rather a free function it is used like so. (the member function version deals with char*).
std::string str;
std::ifstream file("file.dat");
std::getline(file, str);
It is worth noting there are better safer ways to do what you are trying to do like so:
#include <fstream>
#include <string>
#include <vector>
//typedeffing is optional, I would give it a better name
//like vector_str or something more descriptive than ArrayObj
typedef std::vector<std::string> > ArrayObj
ArrayObj load_array(const std::string file_name, char letter)
{
std::ifstream file(file_name);
ArrayObj lines;
std::string str;
while(std::getline(file, str)){
if(str.at(0)==letter){
lines.push_back(str);
}
}
return lines;
}
int main(){
//loads lines from a file
ArrayObj awords=load_array("file.dat", 'a');
ArrayObj bwords=load_array("file.dat", 'b');
//ao.at(0); //access elements
}
don't reinvent the wheel; checkout vectors they are standard and will save you a lot of time and pain.
Final try not to put in using namespace std that is bad for a whole host of reasons I wont go into; instead prefix std objects with std:: so like std::cout or std::string.
http://en.cppreference.com/w/cpp/container/vector
http://en.cppreference.com/w/cpp/string/basic_string/getline
http://en.cppreference.com/w/cpp/string