Making code work with string

The following code only works for integers. How do I make it work for integers AND strings?
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
26
27
28
29
30
31
32
33
34
35
   #include <iostream>
#include<string.h>
using namespace std;

int main(){

	int x,i;


	for(int k=8; k<=13; k++){

	cout<<"Type in "<<k<<endl;
	cin>>x;
	if(x!=k){
		do{
		cout<<"\n No no! Can't you read?! Type in "<<k<<endl;
		cin>>i;

		if(i==k){
			x=i;
		}

		}
		while(x!=k);
	}

	}
	for(int k=8; k<=13; k++){
	cout<<k<<endl;
	}


	return 0;
}
Last edited on
Try using std::string. It can read both integers and strings.

http://www.cplusplus.com/reference/string/string/string/

You'll need to add #include <string> to the top of your code to access std::string.
Last edited on
But now I get a problem with regards to the comparisons. So for I have

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  #include <iostream>
#include<string.h>
#include<string>
using namespace std;

int main(){

	string x;
    string i;



	for(int k=8; k<=13; k++){



	cout<<"Type in "<<k<<endl;
	getline(cin, x, '\n');

	if(x!=k){
		do{
		cout<<"\n No no! Can't you read?! Type in "<<k<<endl;
		getline(cin, i, '\n');

		if(i==k){
			x=i;
		}

		}
		while(x!=k);
	}

	}
	for(int k=8; k<=13; k++){
	cout<<k<<endl;
	}


	return 0;
}
You need to compare apples to apples so here is a snippet that demonstrates this concept.

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	<iostream>
#include	<string>
#include	<cstdlib>

using namespace std;

int main ( ) {
	int value;
	char strValue [80], Result [80];
	
	cout << "Enter a number: ";
	cin >> value;
	cout << "Enter a string: ";
	cin >> strValue;
	
	// Conversion of string to integer
	if ( atoi (strValue) == value )
		cout << "Very good they are the same" << endl;
	
	// Conversion of integer to string
	itoa ( value, Result, 10 );
	cout << "--> " << Result << endl;
	
	return 0;
}

Strings cannot be compared to numeric values without some kind of conversion. There are other ways of doing this, this is just one example
Oops, sorry. I forgot to mention: you can't compare integers and strings. However, you can convert the integer to a string and compare them that way.

The following will output as true

1
2
3
4
5
6
7
8
int i = 4444;
std::string my_string = "4444";

if(std::to_string(i) == my_string)
    std::cout << "They match!" << std::endl;
else
    std::cout << "They don't match" << std::endl;


You will lose precision if you use atoi, so only use that if you are working with integers only. Generally, I try to stick with C++, like std::to_string. atoi actually comes from C.
Last edited on
Topic archived. No new replies allowed.