【发布时间】:2018-11-19 07:54:52
【问题描述】:
在我的应用程序中,我有一个包含我的程序配置的外部文本文件。我正在逐行读取该外部文件并将值添加到数组中。在某些时候,我必须基于数组嵌套循环来处理一些信息。下面是我的代码
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdlib.h>
#include <cstring>
#include <sys/stat.h>
#include <unistd.h>
using namespace std;
string ip_array[0];
string link_array[0];
string conn_array[0];
int readconf(){
int ip_count = 0;
int link_count = 0;
int conn_count = 0;
ifstream cFile ("net.conf");
if (cFile.is_open())
{
string line;
while(getline(cFile, line)){
line.erase(remove_if(line.begin(), line.end(), ::isspace),
line.end());
if(line[0] == '#' || line.empty())
continue;
auto delimiterPos = line.find("=");
auto name = line.substr(0, delimiterPos);
auto value = line.substr(delimiterPos + 1);
if ( name == "IP") {
//cout << value << endl;
ip_array[ip_count] = value;
++ip_count;
}
else if ( name == "LINK") {
//cout << value << endl;
link_array[link_count] = value;
++link_count;
}
}
}
else {
cerr << "file read error.\n";
}
}
int main()
{
readconf();
for( unsigned int a = 0; ip_array[a].length(); a = a + 1 ){
cout << ip_array[a] << endl;
for( unsigned int a = 0; link_array[a].length(); a = a + 1 ){
cout << link_array[a] << endl;
}
}
}
但是当我运行它时,我总是遇到段错误。但是,如果我注释掉一个循环,它工作得很好。当我 COUT readconf 函数上的值时,我得到了正确的值。
【问题讨论】:
-
在哪里发生崩溃?您是否尝试过使用调试器捕获它,并在代码中找到它发生的位置?此外,当使用调试器捕获崩溃时,调试器将允许您检查变量的值,以帮助您找出可能导致崩溃的原因。请了解如何做到这一点,或者至少编辑您的问题,向我们展示它在您的代码中发生的位置(以及所有相关变量的值)。
-
您正在使用长度为零的数组。这意味着他们可以容纳零个项目。
-
一个很大的提示是那些数组。数组及其大小在编译时是固定的,不能扩展。你需要开始了解
std::vector。 -
另外,不要使用全局变量,这是一个坏习惯。也许您也应该学习课程?也许get a couple of good books 并正确学习 C++?
标签: c++ segmentation-fault nested-loops ifstream