退出时,我美元闭环P $ PSS进入(C编程) [英] Exit the loop when I press enter (C-programming)

查看:89
本文介绍了退出时,我美元闭环P $ PSS进入(C编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的计划,我想code有点问题..基本上,我想通过我的一个循环里面输入符号之一,当我做我只是想preSS进入为了退出循环,然后打印出字符串到控制台。然而,这似乎并没有工作,我一直在尝试了几个小时没有得​​到它的抓地力。这是我的code

 的#include<&stdio.h中GT;INT主(INT ARGC,CHAR *的argv []){
    INT I = 0;
    字符文本[我]
    字符符号;    而(1){
       scanf函数(%S,&安培;符号);
       如果(符号== 13){// 13应该是进入ASCII值
                 打破;
       }
       文[I] =符号;
       我++;    }
    的printf(%S,文本);    残培();
    返回0;
}


解决方案

  • %S 读一个字。如果你想阅读 scanf函数字符,请使用%C

  • C字符串是NUL终止,您必须首先在打印之前终止字符串。

  • 字符文本[我] - I 在这一点上为零。您将无法在这里保存您的字符串。无论是知道在编译时的最大尺寸(并在运行时检查追加时)或根据需要动态分配内存。

请注意:从流裸体扫描只是要求了很多麻烦。 preFER读线。

I have a little problem with my program I'm trying to code.. Basically I want to enter a symbol one by one inside my loop and when I'm done I just want to press enter in order to exit the loop and then print out the string to the console. However, this doesn't seem to work and I've been trying for hours without getting the grip of it. This is my code

#include <stdio.h>

int main(int argc, char *argv[]){


    int i = 0;
    char text[i];
    char symbol;

    while(1){
       scanf("%s", &symbol);
       if(symbol == 13){ //13 should be the ascii value for enter
                 break;          
       }
       text[i] = symbol;
       i++;

    }
    printf("%s", text);

    getch();
    return 0;
}

解决方案

  • %s reads a word. If you want to read a character with scanf, use %c.
  • C strings are NUL terminated, you first have to terminate the string before printing it.
  • char text[i] - i is zero at this point. You won't be able to store your string here. Either know the max size at compilation time (and check at runtime when appending) or dynamically allocate memory as needed.

Note: naked scan from the stream is just asking for a lot of trouble. Prefer to read lines.

这篇关于退出时,我美元闭环P $ PSS进入(C编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆