c++ - 我如何处理字母和负数时出错?

标签 c++

请帮助我需要阻止传入的字母和负数 比如错误处理什么的 这是代码

{
printf("\nEnter number of Processes:");
scanf("%d", &n);
for(i=0;i<n;i++)


{
    printf("\nEnter Process ID %d :",i+1);
    scanf("%d", &process[i]);
    printf("\nEnter Process Time %d:",i+1);
    scanf("%d",&ptime[i]);
}

for(i=0;i<n-1;i++)
{
    for(j=i+1;j<n;j++)
    {
        if(ptime[i]>ptime[j])
        {
            temp = ptime[i];
            ptime[i] = ptime[j];
            ptime[j] = temp;
            ptemp = process[i];
            process[i] = process[j];
            process[j] = ptemp;
        }
    }
}
    wtime[0]=0;
for(i=1;i<n;i++)
{
    wtime[i]=wtime[i-1]+ptime[i-1];
    total=total+wtime[i];
}
avg=(float)total/n;
printf("\nProcess ID\t Process TIME\t Waiting TIME\n");
for(i=0;i<n;i++)
    printf("    %d\t           %d\t          %d\n",  process[i],  ptime[i],  wtime[i]);
printf("\nTotal Waiting Time: %d \nAverage Waiting Time: %f", total, avg);

提前致谢需要完成它嘿嘿嘿

最佳答案

简单方法:检查错误,如果有错误则终止。

// add #include <cstdlib> at the beginning of your code to use exit()

{
printf("\nEnter number of Processes:");
if(scanf("%d", &n)!=1 || n<0)exit(1);
for(i=0;i<n;i++)


{
    printf("\nEnter Process ID %d :",i+1);
    if(scanf("%d", &process[i])!=1 || process[i]<0)exit(1);
    printf("\nEnter Process Time %d:",i+1);
    if(scanf("%d",&ptime[i])!=1 || ptime[i]<0)exit(1);
}

更新:

要通过一个exit() 完成所有退出,使用标志是个好主意。 这样,更容易进行其他操作,例如打印错误消息。

// add #include <cstdlib> at the beginning of your code to use exit()

{
bool error_found = false;
printf("\nEnter number of Processes:");
if(scanf("%d", &n)!=1 || n<0)error_found = true;
else
{
    for(i=0;i<n;i++)


    {
        printf("\nEnter Process ID %d :",i+1);
        if(scanf("%d", &process[i])!=1 || process[i]<0){error_found = true; break;}
        printf("\nEnter Process Time %d:",i+1);
        if(scanf("%d",&ptime[i])!=1 || ptime[i]<0){error_found = true; break;}
    }
}
if (error_found) {
    // some error exists
    puts("MUST NOT ALPHABET OR NEGATIVE NUMBER!");
    exit(1);
}

关于c++ - 我如何处理字母和负数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114932/

相关文章:

c++ - 跨 DLL 边界使用单例

c++ - C++ 的优化技术

c++ - 前向声明 typedef

c++ - c++中gets()函数的多行输入

c++ - 如果任何列中都不需要图像/图标,MFC CListCtrl 是否合适?

c++ - 告诉 clang-format 忽略编译指示

c++ - 在此示例中在 FP 上使用 == 是否安全

c++ - 是否允许以不同于调用 allocator::allocate() 的顺序调用 allocator::deallocate()?

C++98 中关于 __sync_synchronize() 问题的 C++0x 原子实现

c++ - Getline 非常奇怪地读取 csv