簡體   English   中英

當我在while循環中的else語句之后使用增量運算符時,它破壞了整個程序並且它不起作用

[英]when i use Increment operator after else statment in a while loop its broke the whole program and it won't work

當我在終端中運行此代碼時,我得到一個空白行,當我移動“i++;”時它什么也不等。 在“while(str[i]!='\0')”下它可以工作,但這不是我想要的,有什么幫助嗎?

int main(){
    printf("hello kiddo");
    char str[20]="hel a awdaw dwa";
    int i=0;
    char *cleanstring;

    while(str[i]!='\0'){
        if(str[i]==' '){
            continue;   
        }
        else{
            printf("%c",str[i]);    
        }
        i++;
    }

    return 0;
}

我不知道這段代碼有什么問題

除了 Johnny Mopp 的評論之外,請注意將 \n 添加到您的 printf 時的區別,您的程序需要刷新字符並且直到行尾才會刷新,正如他所說,自從循環卡住以來,這種情況永遠不會發生。

int main() {
  printf("hello kiddo");
  char str[20] = "hel a awdaw dwa";
  int i = 0;
  char * cleanstring;

  while (str[i] != '\0') {
    if (str[i] != ' ') {
      printf("%c\n", str[i]);
    }
    i++;
  }

  return 0;
}

我解決了這個問題,像這樣編輯“如果條件”

while(str[i]!='\0'){
        //if(str[i]==' '){
        //    continue;   
        //}
        //else{
        //   printf("%c",str[i]);    
        //}
        //i++;

        if(str[i]!=' '){
            strncat(cleanstring,&str[i],1);
        }           
        i++;

    }

代碼無緣無故地長了,現在更好了,但是,仍然想知道為什么它在第一次不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM