Я пытаюсь создать программу, которая получит строку и выведет заглавную версию. Мой код работает, однако, как только он перебирает строку и меняет ее, она сразу же падает, и я не совсем уверен, почему. Вот мои две части кода.
/*This program is to intended to receive a string and return a version of it in all upper case*/
#include <iostream>
#include <string>
#include <locale>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++;)
std::cout << std::toupper(str[i]); //A loop which goes through each digit of the string
break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
/*This program calls a function to make a string in upper case*/
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
#include "toUpper1.h" //Calls the header file which contains the loop
using namespace std;
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
cout<<toUpper(input); //The command that causes the user input string to be transformed into upper case
return 0;
}
Вы нарушаете функцию, не возвращая ничего. Используйте {} для закрытия циклов, если вы хотите использовать break
prog.cpp: 16: 5: ошибка: оператор break не в цикле или перерыве коммутатора;
Также у вашего цикла есть дополнительный; в конце.
std::cout
и std::toupper
бесполезны, поскольку вы уже включаете namespace std;
и почему вы используете break;
? в этом нет необходимости. просто пиши
for (int i=0; i<str.length(); i++)
cout << toupper(str[i]);
Удалить разрыв;
Вы можете сделать строку в верхнем регистре, используя приведенный ниже код
Ускорять строковые алгоритмы:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Или используйте так
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++)
str[i] = std::toupper(str[i]); //A loop which goes through each digit of the string
//break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
//The command that causes the user input string to be transformed into uppe case
cout << toUpper(input);
cout << std::endl << "The original string is" << input << std::endl;
return 0;
}
EDIT: обратите внимание, что сохранение подписи функции, как указано выше (string toUpper ( string str)
, как и требовалось), мы делаем некоторые дополнительные строковые копии и, самое главное: мы НЕ модифицируем исходную строку (excute code и см. результат последнего cout
.
string toUpper( string )
Вы не преобразуете строку, вы выводите ее преобразование в функцию.
вместо
std::cout << std::toupper(str[i]);
использование
str[i]=std::toupper(str[i]);
И переместите всю печать из функции. Изменение строки не включает печать!
Обратите внимание на ответ @bbdude95.
Вместо
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input;
использование
char input[256];
cout << "Please type in a word:\n>";
cin.getline( input, 256, '\n' );
break;
заявление.