如何在C正确地输入一个字符串 [英] How to correctly input a string in C

查看:235
本文介绍了如何在C正确地输入一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在学习C,所以我想作一个程序,要求用户输入一个字符串,并输出已输入的字符数,code编译罚款,当我输入只是1个字符它确实很好,但是当我输入2个或更多字符,无论输入怎样的角色数,它总是会说只有一个字符和崩溃之后。这是我的code,我无法弄清楚什么是错的。

I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fine, when I enter just 1 character it does fine, but when I enter 2 or more characters, no matter what number of character I enter, it will always say there is just one character and crashes after that. This is my code and I can't figure out what is wrong.

int main(void)
{
    int siz;
    char i[] = "";

    printf("Enter a string.\n");
    scanf("%s", i);

    siz = sizeof(i)/sizeof(char);

    printf("%d", siz);
    getch();
    return 0;
}

目前我正在学习编程,所以如果有一种方法使用相同的scanf()的函数来做到这一点我将AP preciate是因为我还没有学会如何使用的其他功能,可能获得'不懂它是如何工作的。

I am currently learning to program, so if there is a way to do it using the same scanf() function I will appreciate that since I haven't learned how to use any other function and probably won't understand how it works.

推荐答案

请,忘了 scanf函数存在。您正在运行之中,而您理解的经验不足造成的主要问题,将继续当你有经验,甚至咬你 - 直到你停止

Please, FORGET that scanf exists. The problem you are running into, whilst caused mostly by your understandable inexperience, will continue to BITE you even when you have experience - until you stop.

这是为什么:

scanf函数将读取输入,并把结果在字符缓冲器您所提供。但是,它的不作任何检查,以确保有足够的空间。如果需要比你提供更多的空间,这将覆盖其他存储位置 - 往往带来灾难性的后果。

scanf will read the input, and put the result in the char buffer you provided. However, it will make no check to make sure there is enough space. If it needs more space than you provided, it will overwrite other memory locations - often with disastrous consequences.

一个更安全的方法是使用与fgets - 这是做大致同样的事情 scanf函数 A的功能,但它为您创造空间将只读取尽可能多的字符(或:你的的创建空间)。

A safer method uses fgets - this is a function that does broadly the same thing as scanf, but it will only read in as many characters as you created space for (or: as you say you created space for).

其他观察:的sizeof 只能评估大小的在编译时已知的:由一个基本类型所采取的字节数(INT,双等)或固定阵列的大小(例如INT I [100])。它不能被用来确定节目期间的大小(如果大小是改变一物)。

Other observation: sizeof can only evaluate the size known at compile time : the number of bytes taken by a primitive type (int, double, etc) or size of a fixed array (like int i[100];). It cannot be used to determine the size during the program (if the "size" is a thing that changes).

您的程序是这样的:

#include <stdio.h>
#include <string.h>

#define BUFLEN 100          // your buffer length

int main(void)    // <<< for correctness, include 'void'
{
    int siz;
    char i[BUFLEN];    // <<< now you have space for a 99 character string plus the '\0'

    printf("Enter a string.\n");
    fgets(i, BUFLEN, stdin);   // read the input, copy the first BUFLEN characters to i

    siz = sizeof(i)/sizeof(char);  // it turns out that this will give you the answer BUFLEN
                                   // probably not what you wanted. 'sizeof' gives size of array in
                                   // this case, not size of string
                                   // also not

    siz = strlen(i) - 1;           // strlen is a function that is declared in string.h
                                   // it produces the string length
                                   // subtract 1 if you don't want to count \n
    printf("The string length is %d\n", siz);  // don't just print the number, say what it is
                                               // and end with a newline: \n
    printf("hit <return> to exit program\n");    // tell user what to do next!
    getc(stdin);
    return 0;
}

我希望这有助于。

I hope this helps.

更新你问的合理的后续问题:我怎么知道该字符串是太长

update you asked the reasonable follow-up question: "how do I know the string was too long".

灵感看到这个code片断:

See this code snippet for inspiration:

#include <stdio.h>
#include <string.h>

#define N 50

int main(void) {
  char a[N];
  char *b;

  printf("enter a string:\n");

  b = fgets(a, N, stdin);

  if(b == NULL) {
    printf("an error occurred reading input!\n"); // can't think how this would happen...
    return 0;
  }

  if (strlen(a) == N-1 && a[N-2] != '\n') {       // used all space, didn't get to end of line
    printf("string is too long!\n");
  }
  else {
    printf("The string is %s which is %d characters long\n", a, strlen(a)-1); // all went according to plan
  }

}

请记住,当你有空间N个字符,最后一个字符(在位置 N-1 )必须是一个'\\ 0',自与fgets 包括的'\\ n'您可以输入最大的字符串是真的 N-2 字符。

Remember that when you have space for N characters, the last character (at location N-1) must be a '\0' and since fgets includes the '\n' the largest string you can input is really N-2 characters long.

这篇关于如何在C正确地输入一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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