I am C++ illiterate.

All im trying to do is make the for loop break when the nth element of array c is a space ' '. Any help would be appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

 	string c;
	getline(cin, c);

	for (int n = 0; n != -1; n++)
	{
		if (c[n] == ' ')
		{
			n = -1;
		}
		
	}
Why not use that as the condition.

1
2
3
4
for(int n = 0; c[n] != ' '; ++n)
{
    std::cout << c[n] << " is not a space" << std::endl;
}


The reason yours doesn't work is because for loops increment at the end so it would really be equal to 0 :P You could however change it to -2 since -2 + 1 == -1.


The for loop really looks like:

1
2
3
4
5
6
7
8
9
int n = 0;
while( n != -1 )
{
    if(c[n] == ' ')
    {
        n = -1;
    }
    ++n;
}


You can also explicitly use the keyword break to break out of a loop though many people do not like using break statements for things like this but instead use a better condition as the first example I showed c[n] != ' ' I would also make sure you do not exceed the size of the string.

Another method would be to use a stringstream depending on what you are trying to do. http://www.cplusplus.com/reference/sstream/istringstream/
Last edited on
Yep sorry i went full retard im just going to use that as a condition thanks for the help
Topic archived. No new replies allowed.