// Exercise in string manipulation
#include <iostream>
#include <string>
void prtname(str);
usingnamespace std;
int main()
{
string input;
cout << "Please enter the name of a bird with long legs: ";
cin >> input;
prtname(input);
return 0;
}
void prtname(str)
{
cout << "The birds name is: " << str;
}
Yes, because "str" is not given a type, the program doesn't know what type to give it. This is probably what you wanted to do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <string>
void prtname(std::string str);
int main() {
std::string input;
std::cout << "Please enter the name of a bird with long legs: ";
std::cin >> input;
prtname(input;
return 0;
}
void prtname(std::string str) {
std::cout << "The bird's name is: " << str;
}
Just in case you didn't know, std::string, std::cout etc. are the same as normal, it is just what you type if you don't use the std namespace. In general, its better to avoid usingnamespace std;, because it leads to some errors that may not be obvious, such as if you declare a global variable called "left" or something.
I spoke to soon. This line: cout << "The birds name is: " << str; only displays the first word in the string.
This line: cout << "The lenght of the name is: " << str.length();
only displays the length of the first word.
// Exercise in string manipulation
#include <iostream>
#include <string>
void prtname(std::string str);
usingnamespace std;
int main()
{
string input;
cout << "Please enter the name of a bird with long legs: ";
cin >> input;
prtname(input);
return 0;
}
void prtname(std::string str)
{
cout << "The birds name is: " << str;
cout << "The lenght of the name is: " << str.length();
}
Ah, thats because "cin" only takes in up to the first space, tab or linefeed. If you want to get everything up to the new line, use getline, like this:
#include <iostream>
#include <string>
void prtname(std::string str);
int main() {
std::string input;
std::cout << "Please enter the name of a bird with long legs: ";
std::getline(std::cin, input);
prtname(input);
return 0;
}
void prtname(std::string str)
{
std::cout << "The birds name is: " << str << std::endl;
std::cout << "The lenght of the name is: " << str.length() << std::endl;
}
Yes, that works fine. I have been using arrays, pointers, and etc (c style) to manipulate strings. It looks like using strings are a little easier.
Thanks
// Exercise in string manipulation
#include <iostream>
#include <string>
void prtname(std::string str);
usingnamespace std;
int main()
{
std::string input;
std::cout << "Please enter the name of a bird with long legs: ";
std::getline(std::cin, input);
prtname(input);
return 0;
}
void prtname(std::string str)
{
std::cout << "The birds name is: " << str << std::endl;
std::cout << "The lenght of the name is: " << str.length() << std::endl;
}