简体   繁体   English

在一行C上将字符串的各个字符转换为ASCII值

[英]Converting individual characters of a string into ASCII values on one line, C

keep in mind i'm a complete beginner and i'm still getting acclimated to the programming vocabulary. 请记住,我是一个完整的初学者,但是我仍然对编程词汇有所适应。

When I run the debug from visual studio, the command prompt comes up with "Enter any string: " but when I enter something, i get "Exception thrown blah blah blah". 当我从Visual Studio运行调试时,命令提示符出现“输入任何字符串:”,但是当我输入内容时,出现“异常抛出等等等等”。 What is going wrong? 怎么了? Any help and criticism is greatly appreciated. 任何帮助和批评都将不胜感激。 I've been losing my mind over this for 4 hours now. 我已经为此失去了4个小时的时间。

Heres my code: 这是我的代码:

int main(){

    char str[100];
    int i=0;

    printf("Enter any string: ");
    scanf_s("%s",str);

    printf("ASCII values of each characters of given string: ");
    while(str[i])
         printf("%d ",str[i++]);


    return 0;
}

The scanf_s() function must be used with a third argument to indicate the max length of the string ie scanf_s("%s", str, 100); scanf_s()函数必须与第三个参数一起使用以指示字符串的最大长度,即scanf_s("%s", str, 100);

BTW scanf_s() is specific to Microsoft Visual Studio so it's less portable so I don't recommend it and str isn't a really good variable name 顺便说一句scanf_s()特定于Microsoft Visual Studio,因此它的可移植性较差,因此我不推荐这样做,并且str不是一个很好的变量名

The posted code is: 发布的代码是:

  1. not portable 不便携
  2. contains 'magic' (not basis for value) numbers 包含“魔术”(不是价值的基础)数字
  3. spreads the variable i declaration far from its' usage 将变量i声明散布到与其用法不符的地方
  4. will not input past a 'white space' character 不会输入超过“空白”字符的字符

The following code corrects those problems, checks for errors, and compiles cleanly 以下代码纠正了这些问题,检查了错误并进行了干净地编译

#include <stdio.h>   // scanf(), printf(), perror()
#include <stdlib.h>  // exit(), EXIT_FAILURE

#define MAX_STR_LEN (100)

int main( void )
{

    char str[ MAX_STR_LEN ];

    printf("Enter any string: ");
    if( NULL == fgets( str, sizeof(str), stdin ))
    {
        perror( "fgets failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("ASCII values of each characters of given string: ");
    for( size_t i=0; str[i]; i++ )
         printf("%d ",str[i]);


    return 0;
}

Note: the above code will input the newline and print it (10 on linux) You might want to use something to eliminate the newline, so insert the following, right after the call to fgets() : 注意:上面的代码将输入换行符并进行打印(在Linux上为10),您可能想使用一些东西来消除换行符,因此请在调用fgets()之后插入以下内容:

char *newline = NULL;
if( NULL != ( newline = strstr( str, "\n" ) ) )
{ // carriage return found
    *newline = '\0';
}

This method of eliminating the newline char means the code also needs: 这种消除换行符的方法意味着代码还需要:

#include <string.h> // strstr()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM