+ 2
c++ ! operator not working
I have a line of code like this: for (int y = 0; true; ++y) { if (!stringArr[y]) { iter = y; break; } } At runtime I get an error telling me there is "no match for operator!". Why? Is this illegal in c++?
12 Respuestas
+ 2
Oh I'm sorry, I didn't make this clear, stringArr is a string array, and I don't think string arrays are able to null terminate. Could you tell me more about std::string[], or how I could check if an item exists?
+ 1
Yes I am trying to check whether stringArr[y] exists or not
+ 1
You can try declare stringArr as std::string[].
+ 1
I can tomorrow, I'll get back with you guys
+ 1
In case if your stringArr is just a string you should compare y and stringArr.size().
In case you need iterate through string's characters it's better to use for(char s : stringArr) form of the for loop.
+ 1
Here is the full code:
#include <iostream>
#include <cstdlib>
using namespace std;
string combiner;
string sentence;
int iter;
void splitString() {
string stringArr[sentence.length()];
for (int i = 0; i < sentence.length(); ++i) {
if (sentence[i] == ' ' && i != 0) {
for (int g = 0; g < i; ++g) {
combiner += sentence[g];
if (g + 1 == i) {
for (int y = 0; true; ++y) {
if (!stringArr[y]) {
iter = y;
break;
}
}
stringArr[iter] = combiner;
combiner = "";
break;
}
}
}
}
}
int main() {
cin >> sentence;
splitString();
return 0;
}
This is an attempt to split an inputted string into separate words based on a space.
By the way Sergey, stringArr.size() gave me the same error that stringArr.length() did, but thanks for trying
+ 1
if(stringArr [y].empty());
Also you should limit your loop
for(int y=0; y<stringArr.lenght();y++)
Actually you don't need this loop, because iter already have place, where combiner was stored previously. Just do stringArr[iter++] = combiner;
Unfortunately your code don't split sentence in words. You need only one loop to do it. Something like this:
for (char c : sentence)
if(c !=" ")
combiner += c;
else if(!combiner.empty())
stringArr[iter++].swap(combiner);
+ 1
Can you even split a string into words? It seems like c++ automatically cuts the string off after the first space