gpt4 book ai didi

c++ - 我的 for 循环不断循环并导致程序崩溃

转载 作者:行者123 更新时间:2023-12-01 22:59:33 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,该程序将接收字符串并输出该字符串的大写版本。我的代码可以工作,但是一旦它循环遍历字符串并更改它,它就会立即崩溃,我不完全确定为什么。这是我的两段代码。

/*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;
}

最佳答案

您可以使用下面的代码将字符串变为大写

增强字符串算法:

#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);

关于c++ - 我的 for 循环不断循环并导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com