atoi()将输出设为0尽管字符串有整数

时间:2016-04-22 11:48:46

标签: c

以下是代码:

   var k = "function(); a = a + 1;"

这里的问题是,尽管我输入了任何消息,但O / P始终为0.我尝试了 #include <stdio.h> #include <stdlib.h> #include <math.h> int main() //main function { // Body of the main function starts here. double c5,c0,semitone_ratio,frequency; //Defining the middle C, the lowest note in MIDI, the ratio and frequency. char message[256]; int midinote = 0; char* result; semitone_ratio = pow(2,1/12.0); //Calculating the semitone ratio. c5 = 220.0 * pow(semitone_ratio, 3); //Calculating the Middle C Frequency using A5 = 440 Hz and raising it up 3 notes. c0 = c5 * pow(0.5,5); //Calculating C0 by shifting it down 5 octaves //User Interface printf("Enter MIDI note (0-127) : \n"); scanf("%s", message); printf("%s", message); if(result == NULL){ printf("There was an error reading the input"); return 1; } if(message[0] = '\0') { printf("No input detected"); return 1; } midinote = atoi(message); if(midinote <0){ printf("Sorry - %s is a bad MIDI note number", message); return 1; } if(midinote > 127) { printf("Sorry - %s is above the range needed", message); } frequency = c0 * pow(semitone_ratio, midinote); printf("The frequency for the %d MIDI note is %f\n",midinote,frequency); return 0; } 而不是scanf(),结果而不是消息(gets()而不是{ {1}} - &gt;处理const问题)但是同样的错误。我做错了什么?

2 个答案:

答案 0 :(得分:5)

if (message[0] = '\0') {
    printf("No input detected");
    return 1;
}

使用==

if (message[0] == '\0') {
    printf("No input detected");
    return 1;
}

答案 1 :(得分:2)

这条线是罪魁祸首:

if(message[0] = '\0') {

您实际上正在将message重置为空字符串。然而,您想要检查message是否为空。

使用==进行比较:

if(message[0] == '\0') {