Hey, I wrote(tried lol) a program that would take the users input and then reverse the words e.g. if you input " one two three " it would output " three two one" by splitting up each word and storing them in an array and displaying them by the highest element working downwards.
#include <iostream>
#include <string>
#include <cstring>
int main()
{
std::string str, strTemp, words[20];
char *cstr, *tok;
int i = 0, counter = 0;
std::cout << "Please input a string to be word reversed: ";
std::getline(std::cin, str);
cstr = newchar[str.length()+1];
strcpy(cstr, str.c_str());
tok = strtok(cstr, " ,.?!-");
while(tok!=NULL)
{
words[i++] = tok;
tok = strtok(NULL, " ,.?!-");
counter++;
}
for(counter; words!=NULL;counter--)
{
std::cout << counter << " ";
std::cout << words[counter] << "\n";
}
std::cin.get();
return 0;
}
Then i tried to change it and clearly changed the wrong place because I was getting the same form of error but can you tell me if this version would be better:
Your problem (in the original) is in line 26.
Firstly, words is an array. Writing words without an index returns the adress to its first element. This value can never be NULL. Try counter>=0 instead.
Now your code should work, but the first line will be empty. That's becouse, if you input "one two three", counter equals three, but in array third element is words[2] , becouse arrays start counting from 0. Just subtract one from counter before the for loop.
hope this helps
:) Thank you. And yes I know about "writing words without an index returns the adress to its first element." but I was receiving an error when I was putting in values in the []