【问题标题】:C user input not working (c, lua)C 用户输入不起作用(c,lua)
【发布时间】:2014-07-19 00:16:31
【问题描述】:

我正在尝试用 c 和 lua 制作一个简单的计算应用程序。但由于某种原因,它正在根据输入来处理命令。我知道代码无用且不切实际,但我正在学习使用 lua (luaJIT)、c api,所以请多多包涵。当我运行此代码时,它会获取用户输入(即添加),但随后什么也不做并跳到代码的末尾。但是我把它放在一个无限循环中来阻止它,但它仍然跳过 if 语句中的代码。有想法该怎么解决这个吗?任何帮助表示赞赏。谢谢!

C 代码:

int main()

{
fflush(stdin);
int status;
int trace = 1;
int x = 0;
lua_Number lua_tonumber (lua_State *L, int index);
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaJIT_setmode(L, trace,LUAJIT_MODE_ALLFUNC|LUAJIT_MODE_ON);
luaL_dofile(L,"fuel.lua");

while(x == 0){
printf("Enter a op (add, sub, multi, div)\n");
scanf("%s", a_word);

if(a_word == "add"){
lua_Number num1;
lua_Number num2;
printf("Enter the first number: ");
scanf("%s", num1);
printf("Enter the second number: ");
scanf("%s", num2);
lua_getglobal(L, "add");
lua_pushnumber(L, num1);
lua_pushnumber(L, num2);
lua_pcall(L,2,1,0);
int resut = lua_tonumber(L,-1);
printf("the number is %d\n", resut);
}

else if(a_word == "sub"){
lua_Number num1;
lua_Number num2;
printf("Enter the first number: ");
scanf("%d", num1);
printf("Enter the second number: ");
scanf("%d", num2);
lua_getglobal(L, "sub");
lua_pushnumber(L, num1);
lua_pushnumber(L, num2);
lua_pcall(L,2,1,0);
int resut = lua_tonumber(L,-1);
printf("the number is %d\n", resut);
}

else if(a_word == "multi"){
lua_Number num1;
lua_Number num2;
printf("Enter the first number: ");
scanf("%s", num1);
printf("Enter the second number: ");
scanf("%s", num2);
lua_getglobal(L, "mult");
lua_pushnumber(L, num1);
lua_pushnumber(L, num2);
lua_pcall(L,2,1,0);
int resut = lua_tonumber(L,-1);
printf("the number is %d\n", resut);
}

else if(a_word == "div"){
lua_Number num1;
lua_Number num2;
printf("Enter the first number: ");
scanf("%s", num1);
printf("Enter the second number: ");
scanf("%s", num2);
lua_getglobal(L, "divi");
lua_pushnumber(L, num1);
lua_pushnumber(L, num2);
lua_pcall(L,2,1,0);
int resut = lua_tonumber(L,-1);
printf("the number is %d\n", resut);
}
}
}

lua 文件:

add = function(x,y)
return x+y
end

sub = function(x,y)
return x-y
end

mult = function(x,y)
return x*y
end

divi = function(x,y)
return x / y
end

【问题讨论】:

    标签: c if-statement lua


    【解决方案1】:

    在 c 中,您使用 strcmp 比较“字符串”。

    strcmp(first_char*, scnd_char*) 
    

    如果它们相等则返回 0,如果 first 在字典上分别更大或更小,则返回正值或负值。

    更多阅读: http://en.cppreference.com/w/c/string/byte/strcmp

    它适用于 c++,但也适用于此处。

    我相信你需要做的是更换:

    if(a_word == "add") 
    

    与:

    if(strcmp(a_word, "add) == 0)
    

    ..等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      相关资源
      最近更新 更多