名字不会出现在我的程序的底部部分
Name wont appear in the bottom part of my program
这个程序用于我的分配,但程序的底部部分没有显示输入的名称,为什么?你们可以在Dev++中测试一下,看看它是如何工作的。
#include<stdio.h>
int main(){
char n4m3[100],Pos;
int rt,hr,gI,T,td,ss=100,pi=100,hc=100,NetIn;
printf(" ==Employee Salary==");
printf("n Name:");
scanf(" %s",&n4m3);
printf("n -Position- n C-CEOn V-VPn S-Supervisorn T-Team Leader");
printf("n Postion:");
scanf(" %s",&Pos);
if (Pos=='C'||Pos=='c')
{
rt=500;
printf("n CEO Rate:500");
}
else if (Pos=='V'||Pos=='v')
{
rt=400;
printf("n VP Rate:400");
}
else if (Pos=='S'||Pos=='s')
{
rt=300;
printf("n Supervisor Rate:300");
}
else if (Pos=='T'||Pos=='t')
{
rt=200;
printf("n Team Leader Rate:200");
}
else printf(" Invalid Input");
printf("n Number of Hours Worked:");
scanf("%d",&hr);
printf("n ==Summary==");
gI=rt*hr;
printf("n Gross Income:%d",gI);
if (gI>=4000)
T=gI*.4;
else if (gI>=3000)
T=gI*.3;
else if (gI>=2000)
T=gI*.2;
else if (gI>=1000)
T=gI*.1;
printf("n Tax:%d",T);
td=T+ss+pi+hc;
printf("n Total Deductions:%d",td);
NetIn=gI-td;
printf("n Net Income is %d",NetIn);
printf("n----------------------");
printf("n Mr./Ms. %s your net income is %d",n4m3,NetIn);
}
这部分应该显示用户的姓名和净收入,但它没有显示姓名
它不工作,因为scanf
想要一个char *
,而你正在传递一个char (*)[100]
。要解决这个问题,请记住,数组是一个连续的内存块,数组的名称是指向该内存开始的指针。因此,n4m3
已经是一个char *
,不需要把它的地址和&
取走。
行应该是scanf(" %s",n4m3); //no '&'
。
我是在启用警告的情况下编译代码时发现这个问题的。你应该总是这样做!在Linux或Mac上使用clang标志-Wall -Wextra -pedantic
进行编译会对这段代码产生几个警告。相关的是:
tmp.cpp:9:13: error: format specifies type 'char *' but the argument has type
'char (*)[100]' [-Werror,-Wformat]
scanf(" %s",&n4m3);
~~ ^~~~~
谷歌错误带我到这里,这解决了问题。另一个警告是:
tmp.cpp:51:10: error: variable 'T' is used uninitialized whenever 'if' condition
is false [-Werror,-Wsometimes-uninitialized]
else if (gI>=1000)
^~~~~~~~
tmp.cpp:54:24: note: uninitialized use occurs here
printf("n Tax:%d",T);
^
tmp.cpp:51:6: note: remove the 'if' if its condition is always true
else if (gI>=1000)
^~~~~~~~~~~~~
tmp.cpp:5:15: note: initialize the variable 'T' to silence this warning
int rt,hr,gI,T,td,ss=100,pi=100,hc=100,NetIn;
^
= 0
有更多的警告,我将让你的编译器(一旦你设置正确)找到。在Windows上,通过使用这些说明来提高Visual Studio的警告级别。如果您让编译器为您分析代码,您将节省许多小时的工作。
当你输入一个没有空格的字符串时,它会工作得很好。但是如果你要输入一个带有空格的字符串,它的行为会改变,因为它只会读取字符串到空格。
你可以在你的代码中使用getline或fgets或sscanf来代替scanf .即
尝试替换行:
scanf(" %s",&n4m3);
fgets(n4m3,100,stdin);
工作正常。在程序结束后,带有result的命令行窗口关闭,因此您无法看到它。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 名字不会出现在我的程序的底部部分
- 添加图像只是到底部或顶部的QT应用程序与样式表(QStyle)