这个程序为什么会崩溃?解决方法
这个程序为什么会崩溃?
这个程序将每个输入到vector对象中的字符串都转换为大写字母并输出,可是为什么我输完并且ctrl+z回车以后程序就会崩溃呢?
------解决方案--------------------
这个程序将每个输入到vector对象中的字符串都转换为大写字母并输出,可是为什么我输完并且ctrl+z回车以后程序就会崩溃呢?
- C/C++ code
#include <iostream> #include <vector> #include <string> #include <cctype> using namespace std; int main() { vector<string> strvec; string str; while (cin >> str) { strvec.push_back(str); } if (strvec.size() == 0) { cout << "No string?!" << endl; return -1; } for (vector<string>::size_type ix; ix != strvec.size(); ++ix) { for (string::size_type i = 0; i != strvec[ix].size(); ++i) { strvec[ix][i] = toupper(strvec[ix][i]); cout << strvec[ix] << " "; if ((ix + 1) % 8 == 0) cout << endl; } } return 0; }
------解决方案--------------------
- C/C++ code
for (vector<string>::size_type ix=0; ix != strvec.size(); ++ix)//ix初始值要为0
------解决方案--------------------
- C/C++ code
for (vector<string>::size_type ix; ix != strvec.size(); ++ix) //ix没有初始化 //改为 for (vector<string>::size_type ix=0; ix != strvec.size(); ++ix)
------解决方案--------------------
你这循环有问题啊!
------解决方案--------------------
vector<string>::size_type ix;ix没有初始化。
应该这样写:
for (vector<string>::size_type ix = 0; ix != strvec.size(); ++ix)
{
for (string::size_type i = 0; i != strvec[ix].size(); ++i)
{
strvec[ix][i] = toupper(strvec[ix][i]);
cout << strvec[ix] << " ";
if ((ix + 1) % 8 == 0)
cout << endl;
}
}