如果使用逗号“,”,则程序出错在一个名字 [英] Error in program if a put a comma ", " in a name

查看:153
本文介绍了如果使用逗号“,”,则程序出错在一个名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如。

如果我输入名称Bob Marley。该程序将有效。

但如果我输入像Marley这样的名字,鲍勃。程序崩溃了。



我尝试过:



这是我做的程序。





For example.
If I typed the name Bob Marley. The program will work.
But if I type the name like this Marley, Bob. The program crashes.

What I have tried:

This is the program that I have made.


#include <iostream>
#include <string>

using namespace std;

int main()
{
 string name[20];
 int grade[20];
 int index[20];
 int i, j;

 for(i=0;i<=20;i++)
 {
  cout << "Please enter name: ";
  cin >> name[i];
  cout << "Please enter grade: ";
  cin >> grade[i];
 }

 for(i=0;i<=20;i++)
 {
  index[i]=i;
 }

 for(i=0;i<=20;i++)
 {
  for(j=i+1;j<=20;j++)
  {
   int temp;
   
   if(name[index[i]] > name[index[j]])
   {
    temp = index[i];
    index[i] = index[j];
    index[j] = temp;
   }
  }
 }
 cout << endl;

 for(i=0;i<=20;i++)
 { 
  cout << name[index[i]] << "        "
   << grade[index[i]] << endl;
 }

 cin.ignore();
 cin.get();

 
}

推荐答案

string name[20];



这不是20个字符串的数组,这是一个大小为20的字符串。




当你不明白你的代码在做什么或为什么它做它的作用时,答案是调试器

使用调试器查看代码正在执行的操作。只需设置断点并查看代码执行情况,调试器允许您逐行执行第1行并在执行时检查变量,这是一个令人难以置信的学习工具。



调试器 - 维基百科,免费的百科全书 [ ^ ]

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

使用Visual Studio 2010进行基本调试 - YouTube [ ^ ]



调试器在这里向您展示您的代码在做什么你的任务是与它应该做的事情进行比较。

调试器中没有魔法,它没有发现错误,它只是帮助你。当代码没有达到预期的效果时,你就接近了一个错误。


This is not an array of 20 strings, this is a string of size 20.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.


你有大小为20的数组。但是在你的所有循环中你迭代超过21个项目: br />
You have arrays with sizes of 20. But in all your loops you are iterating over 21 items:
for(i=0;i<=20;i++)



最后一次迭代你正在访问该项目 array [20] 但允许的索引从0到19.这称为超出限制的访问。无法预测会发生什么。虽然读取只返回错误的值,但写入将覆盖其他数据并可能导致访问冲突。


With the last iteration you are accessing the item array[20] but allowed indexes are from 0 to 19. This is called out of bound access. What happens can't be predicted. While reading just returns wrong values, writing will overwrite other data and may result in an access violation.


这篇关于如果使用逗号“,”,则程序出错在一个名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆