Reputation: 61
Just returned to programming in C++. the errors i get:
request for member begin in sent is of non-class type char[30]
request for member end in sent is of non-class type char[30]
char sent[] = "need to break this shiat down";
for(vector<string>::iterator it=sent.begin(); it!=sent.end(); ++it){
if(*it == " ")
cout << "\n";
else
cout << *it << endl;
}
should i change the char to string or define the vector differently?
Upvotes: 0
Views: 11408
Reputation: 66254
You can also use streaming to throw out the whitespace and throw in newlines.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
stringstream ss("need to break this shiat down.", ios_base::in);
string s;
while (ss >> s)
cout << s << endl;
return EXIT_SUCCESS;
}
Result:
need
to
break
this
shiat
down.
Upvotes: 3
Reputation: 24420
char sent[]
is not std::string
but string literal - but in this very case you can iterate over it:
int main() {
char sent[] = "need to break this shiat down";
for(auto it = std::begin(sent); it!=std::end(sent) - 1; ++it){
if(*it == ' ')
cout << "\n";
else
cout << *it << endl;
}
}
Note that I changed " "
to ' '
- and skipped last null terminating char '\0'
...
Live example: http://liveworkspace.org/code/55f826dfcf1903329c0f6f4e40682a12
For C++03 you can use this approach:
int main() {
char sent[] = "need to break this shiat down";
for(char* it = sent; it!=sent+sizeof(sent) - 1; ++it){
if(*it == ' ')
cout << "\n";
else
cout << *it << endl;
}
}
If this is string literal of size not known at that point - use strlen instead of sizeof...
Upvotes: 2
Reputation: 227558
It has been pointed out in other answers that you are iterating over the wrong type. You should define sent
to be of std::string
type and use std::string::begin()
and std::string::end()
to iterate, or, if you have C++11 support, you have some options for easily iterating over a fixed size array. You can iterate using std::begin
and std::end`:
char sent[] = "need to break this shiat down";
for(char* it = std::begin(sent); it != std::end(sent); ++it){
if(*it == ' ')
std::cout << "\n";
else
std::cout << *it << "\n";
}
or you can use a range-based loop:
char sent[] = "need to break this shiat down";
for (const auto& c : sent)
{
std::cout << c << "\n";
}
Upvotes: 4
Reputation: 32817
Use string
instead of char[]
string sent = "need to break this shiat down";
for(string::iterator it=sent.begin(); it!=sent.end(); ++it){
if(*it == ' ')
cout << "\n";
else
cout << *it << endl;
}
char[]
doesnt have begin and end methods..
Upvotes: 1
Reputation: 77495
Your variable sent
is not of type vector<string>
, but char[]
.
Your for loop however, tries to iterate over a vector of strings.
For a plain array, use C iteration:
int len = strlen(sent);
for (int i = 0; i < len; i++)
Upvotes: 1