Trying to learn how to convert data type of numbers in a string to integers.

I need to write a program for class that requires me to convert numbers in a string to integers. So I wrote a sample program to try to figure out how to but when I try to compile it I get a massive influx of errors. I'm not sure what I'm doing wrong and any help would be greatly appreciated.

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

int main()
{
	string st;
	cout << "Enter numbers: ";
	cin << st;
	for (int i = 0; i < st.length(); i++)
	{
		st[i] = st[i] - '0';
	}
}
i would recommend use stringstream if you want to convert a string to an integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Example program
#include <iostream>
#include <string>
#include <sstream>

int main()
{
  std::string stringval("107");
  std::stringstream converter;
  converter << stringval;
  
  int intval;
  converter >> intval;
  
  std::cout << intval;
  
}
Last edited on
Is there a way I could use this to convert multiple entries in a string at one time?
Topic archived. No new replies allowed.