【发布时间】:2018-03-06 23:17:11
【问题描述】:
我正在开发一个相当简单的优先级调度程序,它接受一个文本文件,其中的行格式为:
[N/S/n/s] number number
我正在尝试将数字转换为双精度格式。我正在尝试使用 stringstream 来执行此操作(这是一个必须在没有 stod 的 Linux 版本上运行的类项目),使用此处的示例作为参考:https://www.geeksforgeeks.org/converting-strings-numbers-cc/
问题是,当我尝试实现我认为应该是相当简单的几行代码来执行此操作时,我遇到了“分段错误(核心转储)”,这似乎与我的尝试直接相关实际将字符串流发送到我创建的双变量。到目前为止,我已经包含了我的代码(显然还远远没有完成),并且还指出了我可以通过输出“made it to here”来执行的最后一行。我对这个问题感到非常困惑,希望能提供任何帮助。请注意,虽然我为了完成而发布了我的整个代码,但只有靠近底部的一小部分与我已经明确指出的问题相关。
代码:
#include <iostream>
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
#include<cstring>
#include<sstream>
#include<cstdlib>
#include <unistd.h>
#include<pthread.h>
#include<ctype.h>
#include <vector>
#include <sys/wait.h>
#include <fstream>
#include<ctype.h>
using namespace std;
struct Train{
public:
char trainDirection;
double trainPriority;
double trainTimeToLoad;
double trainTimeToCross;
};
void *trainFunction (void* t){cout << "placeholder function for "<< t <<endl;}
vector<string> split(string str, char c = ' '){
vector<string> result;
int start = 0;
int end = 3;
int loadCounter = 1;
int crossCounter = 1;
result.push_back(str.substr(start, 1));
start = 2;
while (str.at(end) != ' '){
end++;
loadCounter++;
}
result.push_back(str.substr(start, loadCounter));
start = end + 1;
end = start +1;
while(end < str.size()){
end++;
crossCounter++;
}
result.push_back(str.substr(start, crossCounter));
for(int i = 0; i < result.size(); i++){
cout << result[i] <<"|";
}
cout<<endl;
return result;
}
int main(int argc, char **argv){
//READ THE FILE
const char* file = argv[1];
cout << file <<endl;
ifstream fileInput (file);
string line;
char* tokenPointer;
int threadCount = 0;
int indexOfThread = 0;
while(getline(fileInput, line)){
threadCount++;
}
fileInput.clear();
fileInput.seekg(0, ios::beg);
//CREATE THREADS
pthread_t thread[threadCount];
while(getline(fileInput, line)){
vector<string> splitLine = split(line);
//create thread
struct Train *trainInstance;
stringstream directionStringStream(splitLine[0]);
char directionChar = 'x';
directionStringStream >> directionChar;
trainInstance->trainDirection = directionChar;
if(splitLine[0] == "N" || splitLine[0] == "S"){
trainInstance->trainPriority = 1;
}
else{
trainInstance->trainPriority = 0;
}
stringstream loadingTimeStringStream(splitLine[1]);
double doubleLT = 0;
cout << "made it to here" <<endl;
loadingTimeStringStream >> doubleLT; //THIS IS THE PROBLEM LINE
trainInstance->trainTimeToLoad = doubleLT;
stringstream crossingTimeStringStream(splitLine[2]);
double doubleCT = 0;
crossingTimeStringStream >> doubleCT;
trainInstance->trainTimeToCross = doubleCT;
pthread_create(&thread[indexOfThread], NULL, trainFunction,(void *) trainInstance);
indexOfThread++;
}
}
【问题讨论】:
-
你使用了
argv[1],没有检查参数的数量。你确定你传递了所需的参数吗? -
是的,我还没有实现错误检查,但我确信输入是正确的。
-
如果可以的话,请避开
void *mumbo-jumbo。它可能是源源不断的错误,在 C++ 中几乎从不需要。也就是说,trainFunction承诺返回void*而不会。现在允许编译器生成各种奇特的代码。
标签: c++ string stringstream