0
にファイルからデータを格納するとき、私は、この形式のファイル(「input10」)から数を取り込んでC++プログラムを書いています:C++:コンパイラ固有のセグメンテーションフォールト配列
1 0 12
2 3 24
3 8 9
4 9 2
5 10 3
6 11 4
7 14 8
8 16 10
9 16 3
10 17 12
各番号はに入ります配列p_data[3]
(各行に3つの数字)。
Visual Studioで実行すると、エラーはなく、正しいデータが配列に格納されます。 strncpy
を使用できるように、ここには#define _CRT_SECURE_NO_WARNINGS
が含まれています。 strncpy
が問題の原因かどうかはわかりません。
セグメンテーションフォールト(コアダンプ)
私はデバッグが本当に難しいこの問題を発見しています:
CentOSの端末上でg++ -std=c++11
で実行されている、私は、次のエラーメッセージが表示されます。何かご意見は? C++ 11では
#include <iostream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <fstream>
using namespace std;
void get_processes() {
string curr_line;
ifstream infile("input10");
int p_data[3];
int p = 0;
char line[1024];
while (getline(infile, curr_line)) {
strncpy(line, curr_line.c_str(), sizeof(line));
line[sizeof(curr_line) - 1] = 0;
int p_data_count = 0;
for (int i = 0; line[i] != '\0'; ++i) {
if (line[i] != ' ') {
string num = "";
while (line[i] != ' ') {
num += line[i];
++i;
}
if (p_data_count < 3) {
p_data[p_data_count] = stoi(num);
++p_data_count;
}
}
}
}
infile.close();
}
int main() {
get_processes();
return 0;
}
'sizeof(curr_line)'が間違っています。それは文字列の長さを与えません。私は[良いstd :: string'リファレンス](http://en.cppreference.com/w/cpp/string/basic_string)をお勧めします。 –
そしてなぜ配列 'line'を使って始めるのですか? 'std :: string'の各文字には、' [] 'インデックス演算子を持つ配列と同様にアクセスできます。またはイテレータを使用します。または、範囲ベースの 'for'ループを使用します。私はあなたが[良い初心者の本](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)を読む必要があると思います。 –
私が言ったように、それはVSで動作します。私は主になぜg ++で動作しないのか不思議です。 – jshapy8