the instructions tell me to use it |
- can we get a full copy of the instructions? Perhaps they meant for you to use - [
http://www.cplusplus.com/reference/string/string/compare/ ]? TheIdeasMan has a recommend on using String's comparison operators which would be easier, but the option is available.
There are instances where you might be using a C-language library inside a C++ program, so it's still good to know how to convert between String and Cstring.
String to const Cstring - [
http://www.cplusplus.com/reference/string/string/c_str/ ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
//Lab 9D
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string stringOne, stringTwo;
cout << "Please enter a sentence: ";
getline(cin,stringOne);
cout << "Please enter another sentence: ";
getline(cin,stringTwo);
if (strcmp(stringOne.c_str(),stringTwo.c_str()) == 0)
cout << "The strings are equal" << endl;
else if (strcmp(stringOne.c_str(),stringTwo.c_str()) < 0)
cout << "String one comes before string two" << endl;
else
cout << "String one comes after string two" << endl;
return 0;
}
|
This link shows how to capture a non-const Cstring from a String - [
http://www.cplusplus.com/reference/string/string/copy/ ] Just be certain to add that string terminator at the end, the resulting C-string would not be safe to use without it.
Off topic, but here are some type conversions between Strings and number-types - [
http://www.cplusplus.com/reference/string/ ], check out stoi(), stod(), stoll(), and to_string()
Note: I agree with Againtry: wherever possible just stick to one or the other, converting between the two mostly just adds to wasted computing time. The code example above is just an attempt to closely fit your original code. In real code try to keep string conversions near the edges of your code where interacting with a library or binary file requires it.
@Againtry: I've never really considered the difference between std::istream::getline(cstring, length) and std::getline(istream, string), but there's a possibility for fewer conversions and allocations when used correctly. Thank you, good info.