why wont this compile?!!!

closed account (3bfGNwbp)
It runs fine on IDEONE, but I'm getting errors when I compile it with Visual Studio. Why is this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "StdAfx.h"
#include <iostream>
#include <string>

int main(void) {
	std::string str, final;
	int finalIndex = 0;
	std::cout << "String: ";
	std::cin >> str;
	for(int x = 97; x != 122; ++x) { 
		for(int i = 0; str[i] != '\0'; ++i) {
			if(x == str[i]) {
				final[finalIndex] = x;
				++finalIndex;
			}
			else {
				continue;
			}
		}
	}
	std::cout << "Final: " << final << std::endl;
	std::cin.ignore();
	std::cin.get();
	return 0;
}
Last edited on
What error message do you get?
I can see that you are using a C approach on a C++ string (you are looping through the string to do stuff)

A better way might be to use the functionality of std::string to achieve what you want. Google it.

Also if you put :

1
2
3
using std::cin;
using std::cout;
using std::string;


Then you wont have qualify these all throughout your code. That is you wont have to put std::cout everywhere for example.

Cheers

TheIdeasMan

I think str[i] when i == str.length() will generate an error in debug mode. This is actually not an error according to the latest C++ standard. Hopefully Visual Studio will fix this bug in future versions.

Then you wont have qualify these all throughout your code. That is you wont have to put std::cout everywhere for example.
This is a matter of taste. I find it easier to just put std:: infront of everything. That way it's easy to see that the name is from the standard library and I don't have to put a lot of using directives everywhere.
Last edited on
This statement

1
2
3
4
if(x == str[i]) {
	final[finalIndex] = x;
	++finalIndex;
}


because a memory for string final was not allocated. So you should get a runtime error.
if(x == str[i])
and this is error too because comparing string and int
@chipp
if(x == str[i])
and this is error too because comparing string and int


It is not an error because str[i] is not a string. str[i] is a scalar is a scalar integer type.
my question could be looks very silly: what is scalar integer type?
Scalar is a fancy word for primitive.
1
2
3
for(int i = 0; str[i] != '\0'; ++i) // line 11 in your program

for (int i = 0; i < str.length(); i++) // might be better suited for your needs 


1
2
3
if(x == str[i]) // this will NEVER execute.
// x is always equal to a 2 or 3 digit number in your program
// so comparing it to 1 character in a string isn't useful 


1
2
3
4
5
6
7
8
9
10
else
{
    continue;
}
// when you only have one line of code,
// you can write it like this:
else
    continue;
// but anyways, this doesn't do anything either.
// what are your intentions with this else statement?  
Last edited on
Topic archived. No new replies allowed.