【问题标题】:going reverse in a for loop?在for循环中反转?
【发布时间】:2010-03-21 02:21:50
【问题描述】:

基本上我得到了这个for循环,我希望输入的数字(例如123)被反向打印出来,所以“321”。 到目前为止,它工作正常并在 for 循环时打印出正确的顺序

for(i = 0; i<len ; i++)

但是当我尝试反向打印时出现错误?怎么了?

#include <stdio.h>
#include <string.h>
void cnvrter(char *number);

int main(){
    char number[80];
    printf("enter a number ");
    gets(number);
    cnvrter(number);

    return 0;
}

void cnvrter(char *number){
    char tmp[80];
    int i = 0,len = 0;
    int cnvrtd_digit = 0;
    len = strlen(number);
    printf("\nsize of input %d\n",len);
    for(i = len; i>len ; i--){
        if ( ( number[i] >= '0' ) && ( number[i]<='9' ) ){
            tmp[0] = number[i];
            sscanf(tmp,"%d",&cnvrtd_digit);

        }
        printf("%d\n",cnvrtd_digit);
    }
}

【问题讨论】:

  • 错误,因为它编译但崩溃。

标签: c++ string gcc for-loop


【解决方案1】:

再次查看您的 for 循环:

for(i = len; i>len ; i--){

你正在做i=len,然后测试i&gt;len——除非作业中出现严重错误,否则这永远不会是真的......

顺便说一句,虽然它不相关,但你不应该使用gets,即使在这样一个你从未打算认真使用的程序中。

【讨论】:

  • hmmm 当我使用 for(i = len; i>=0 ; i--) 我得到 0321 打印出来。为什么会出现这个 0?
  • 在 C 和 C++ 中,数组索引从 0 开始,因此对于长度为 3 的字符串,最大有效索引为 2。
  • 你应该使用 i=len-1,而不是 i=len。
【解决方案2】:

您不需要显式的 for-loop 来反转 C++ 中的字符串。您可以使用std::reverse()str.rbegin(), str.rend()

// -*- coding: utf-8 -*-
// $ g++ *.cc && (echo 'abc1d23e->١<-_ f999fff' | ./a.out)
#include <algorithm>  // remove_copy_if
#include <functional> // not1
#include <iostream>
#include <iterator>   // ostream_iterator
#include <string>

int main() {
  using namespace std;

  cout << "enter a number " << flush;               // print prompt
  string str; cin >> str;                           // read until first space
  cout << "\nsize of input " << str.size() << endl;

  remove_copy_if(
      str.rbegin(), str.rend(),                     // traverse in reverse order
      ostream_iterator<string::value_type>(cout, "\n"), // copy to stdout
                                                        // separated by newline
      not1(ptr_fun((int (*)(int))isdigit)));        // remove non-digits
}

运行它:

$ g++ *.cc && (echo 'abc1d23e->١<-_ f999fff' | ./a.out)
enter a number 
size of input 15
3
2
1

【讨论】:

    【解决方案3】:

    您永远不会在 tmp 上推进索引,也永远不会以空值终止它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多