使用for循环

时间:2016-04-29 10:47:01

标签: c++ arrays loops

我正在尝试编写一个简单的程序,它接受一组字符,然后向后吐出。我知道还有很多其他方法可以使用库头函数来缩短它,但我想使用for循环只是为了习惯它们。

#include<stdio.h>
#include<iostream>
using namespace std;

char string1[10];
int count = 0;
char stringy[10];

void enterString()
{
    cout << "please enter a string: " << endl;
    cin >> string1;
}

void stringCounter(const char stringLength[])
{
    //initiate for loop i = 0
    //if stringLength[i] does not does not equal 'i' then carry on
    //increment i
    for (int i = 0; stringLength[i] != '\0'; i++)
    {   
        count++;
    }   
    cout << "size of string is: " << count << endl;
}

void reverseString(int arraySize, char string2[])
{
    int counter = 0;
    for (int i = arraySize; i >= 0; string2[i--])
    {   
        stringy[counter] = string2[i];
        counter++;
    }   
    stringy[count] = '\0';
    cout << stringy << endl;
}

int main()
{
enterString();
stringCounter(string1);
reverseString(count, string1);
return 0;
}

这是整个计划。该程序在函数reverseString中失败。我无法弄清楚如何成功读取char array string2[]的最后一个索引并将其复制到char array stringy的第一个索引中。

2 个答案:

答案 0 :(得分:1)

一,如果用户输入的字符串长度超过10个字符,那么enterString()函数将在cin>>string1处访问该数组之外的数组。因此,最好使用getline来确保您不会阅读超出数组所能容纳的内容。

两,使用当前实现,reverseString()函数将使用空终止符字符写入数组的第一个元素,如果是arraySize<=10,并且尝试显示该字符串将不会向您显示任何内容

此:

 cin >> string1;//will try to access the array out of its bound if user give more than it can hold,i.e 10 characters

 ...

 for (int i = arraySize; i >= 0; string2[i--])
 {   
    stringy[counter] = string2[i];//the first iteration will put the '\0' character as the first elements of stringy
     counter++;
 } 

应改为:

cin.getline(string1,10);//make sure to get not more than 10 characters,including the null terminator

 .....

for (int i = arraySize-1; i >= 0; i--)
{   
    stringy[counter] = string2[i];
    counter++;
} 

答案 1 :(得分:0)

您的计划中存在许多错误。如果这是您正在编译的确切代码,那么它应该抛出许多错误。 以下可能有所帮助。

#include<iostream>

using namespace std;

void reverseString(int , char *);
int stringCounter(const char );

int stringCounter(const char stringLength[])
{
    int count = 0;
    for (int i = 0; stringLength[i] != '\0'; i++)
        count++;
    cout << "size of string is: " << count << endl;
    return count;
}
void reverseString(int arraySize, char string2[])
{
    int counter = 0;
    char stringy[100];
    for (int i = arraySize - 1; i >= 0; i--)
    {
        stringy[counter] = string2[i];
        counter++;
    }
    stringy[counter] = '\0';
    cout << stringy << endl;
}

int main()
{
    char str[] = "string";
    reverseString(stringCounter(str),str);

    return 0;
}