如何在C++中创建for循环

问题描述:

嘿,我有我的程序,我想知道如何添加一个for循环或一个while循环的数组。 我很困惑如何将它们添加到我的代码中以及如何使用它们。如何在C++中创建for循环

#include <iostream> 
using namespace std; 


int main() 
{ 

    char input_string [100]; 
    cout << "Please enter an input string: ";  // print Please enter an input string 
    cin >> input_string;       //user will input string 

    cout << "This is the input string: "<< input_string<<endl; //print this is the input string 

    int mod_int; 
    cout <<"Please enter the modification: ";  // print please enter the modification 
    cin >> mod_int;        //user will enter modification integer 

    cout<<"Modification integer used is: "<< mod_int <<endl; // print modification integer used is 


    cout << (char)(input_string[0] + mod_int); //convert the letter according to the mod int. 

    return 0; 
} 

我想添加根据mod_int修改的整个字符串。 所以可以说我们有一个input_string“hello”,其mod_int是4我希望它显示“lipps”我可以通过复制“cout < <(char)(input_string [0] + mod_int);”多次,但我希望它循环。

+0

尝试编辑您的问题以正确格式化代码。 – Hawkings

+0

@ user5451982你想展示什么?你的'input_string'或整个'string'的特定字符? –

+0

所以你想增加/减少字符串中使用的字母?在这种情况下,hello + 4 = lipps,因为按字母顺序,h + 4 = 1,e + 4 = i,l + 4 = p且o + 4 = s? – Tas

This?

for(int i = 0; i <= mod_int; i++) 
{ 
    cout << (char)(input_string[i] + mod_int); 
} 
+0

它似乎不工作:/我会在“cout Yahya

+0

似乎工作正常:https://ideone.com/L7vUcV – Tas

+0

@tas,注意循环的终止情况不一定匹配字符串的长度。这只适用于C'thulu的恩典。 – user4581301

让这个尝试:

int len = strlen(input_string); 

for(int i = 0; i < len; i++) 
{ 
    input_string[i] += mod_int; 
} 
cout << input_string << endl; 

它把input_string成所期望的输出,然后正常打印字符数组。请注意使用strlen

从学习一些通用编程基础开始。 C++是一门难以学习的语言,因为您需要首先学习C语言。为了真正学习C,你必须知道汇编程序。你的问题表明,不仅你不知道基础知识,而且还试图跳过你的头脑和你不明白的复印代码。因为初学者90%的时间都试图通过复制粘贴来学习。