Convert String to size_t in C++
Last Updated :
28 Nov, 2022
Improve
To convert String to size_t in C++ we will use stringstream, It associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). We must include the stream header file in order to use stringstream. When parsing input, the stringstream class comes in quite handy.
Syntax:
std :: stringstream stream(string_name)
Example:
// C++ Program to declare a string variable without using stringstream.
#include <iostream>
using namespace std;
int main()
{
string s1 = "Hello Geek";
cout << s1 << endl;
string s2;
cin >> s2;
cout << s2 << endl;
return 0;
}
15
1
// C++ Program to declare a string variable without using stringstream.
2
3
4
using namespace std;
5
6
int main()
7
{
8
string s1 = "Hello Geek";
9
cout << s1 << endl;
10
string s2;
11
cin >> s2;
12
cout << s2 << endl;
13
14
return 0;
15
}
Output:
Hello Geek GeeksforGeeks
Example:
// C++ Program to convert the string to size_t using
// stringstream.
#include <iostream>
#include <stream>
#include <string>
using namespace std;
int main()
{
string str = "246810";
// breaking words
stringstream stream(str);
// associating a string object with a stream
size_t output;
// to read something from the stringstream object
stream >> output;
cout << output << endl;
return 0;
}
22
1
// C++ Program to convert the string to size_t using
2
// stringstream.
3
4
5
6
using namespace std;
7
8
int main()
9
{
10
string str = "246810";
11
// breaking words
12
stringstream stream(str);
13
14
// associating a string object with a stream
15
size_t output;
16
17
// to read something from the stringstream object
18
stream >> output;
19
20
cout << output << endl;
21
return 0;
22
}
Output:
246810