I have an input file which I'm reading in with the basic myFile >> variable
since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num>
and to make >>
work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
Asked
Active
Viewed 64 times
-1
![](../../users/profiles/2868510.webp)
Tommy K
- 1,487
- 2
- 24
- 46
-
possible duplicate of [Parse (split) a string in C++ using string delimiter (standard C++)](http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – ha9u63ar Mar 18 '15 at 21:09
4 Answers
1
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
![](../../users/profiles/3795575.webp)
olive007
- 550
- 8
- 23
-
got it, this works, initially I had `value` as a string and it wasn't getting rid of the last `>`, but I changed it and it works. Thanks! – Tommy K Mar 18 '15 at 21:24
0
First to get the middle character out you can just do char myChar = inputString.at(1);
. Then you can do int myInt = (int)myChar;
![](../../users/profiles/4431104.webp)
Nicholas Callahan
- 149
- 1
- 8
-
Incorrect, and also using C-style casts. The stringstream answer above is better, and can also be wrapped in a templated function. – Erik Alapää Mar 18 '15 at 21:18
-
it won't always be a one-digit number though. I'm trying to use .erase() on the string to get rid of the first and last iterator to erase the <> but its not working as I expected. – Tommy K Mar 18 '15 at 21:18
0
Even if you remove the <>
characters, your still importing the file content into a string using >>
so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
![](../../users/profiles/4266707.webp)
Javia1492
- 820
- 8
- 24
0
You can also resort to sscanf
.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}
![](../../users/profiles/434551.webp)
R Sahu
- 196,807
- 13
- 136
- 247