从C 中的文本提取数字---分割故障
extract numbers from text in C++ --- segmentation fault
我有一个包含数字的文本:148,147,148,146,135,22,....几乎有11000个数字。我想将每个奇数的数字(第一个,第三个...)放在阵列(148,148,135 ...)中,而每个偶数均匀的数字(第二,第四...,即147,146,22)...)。运行以下代码我会遇到细分故障错误,我不确定数字是否正确在数组中。你能帮我吗?
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
ifstream infile;
int arraya[11000];
int arrayb[11000];
int i=0;
int noum=0;
char cNum[10];
infile.open ("pairs.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
infile.getline(cNum, 256, ',');
if ( i % 2== 0 )
arraya[i]= atoi(cNum);
else
arrayb[i]= atoi(cNum) ;
i++ ;
}
infile.close();
}
else
{
cout << "Error opening file";
}
for (i=0; i<10;i++){
cout<<arraya[i];
cout<<",";
cout<<arrayb[i];}
return 0;
}
修改
while (infile.good())
{
infile.getline(cNum, 256, ',');
进入
while (infile.getline(cNum, 10, ',')) {
因为cNum
的大小仅为10。
另外,正如@synapse提到的那样,您在数组边界上写下。您需要
if ( noum % 2== 0 )
arraya[i/2]= atoi(cNum);
else
arrayb[i/2]= atoi(cNum);
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream infile;
int arraya[6000];
int arrayb[6000];
int iA = 0;
int iB = 0;
int noum = 0;
char cNum[10];
infile.open("pairs.txt", ifstream::in);
if (infile.is_open()) {
while (infile.getline(cNum, 256, ',')) {
noum = atoi(cNum);
if (noum % 2 == 0)
arraya[iA++] = noum;
else
arrayb[iB++] = noum;
}
infile.close();
} else {
cout << "Error opening file";
}
cout << "Even: " << endl;
for (int i = 0; i < iA; i++) {
cout << arraya[i];
cout << ",";
}
cout << std::endl;
cout << "Odd: " << endl;
for (int i = 0; i < iB; i++) {
cout << arrayb[i];
cout << ",";
}
return 0;
}
您需要拥有一个布尔变量,该变量会声明该数字是偶数或奇数,它也可以通过迭代器来解决,并检查它是否是%2 == 0,这只是其中一个应用程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
ifstream text;
text.open("yourfile", ifstream::in);
if (!text.is_open()) {
cerr << "Error opening file.";
return 1;
}
int arrayA[1000];
int arrayB[1000];
int iA = 0;
int noum = 0;
int iB = 0;
bool odd = true;
string cNum;
while(text >> cNum) {
noum = atoi(cNum.c_str());
if (!odd) {
arrayA[iA++] = noum;
odd = true;
} else {
arrayB[iB++] = noum;
odd = false;
}
}
text.close();
if (!odd)
for (int i = 0; i < iA; i++)
cout << arrayA[i] << ", " << arrayB[i] << endl;
else
for (int i = 0; i < iB; i++)
cout << arrayA[i] << ", " << arrayB[i] << endl;
return 0;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何在C++中从字符串中分割字符
- C++映射分割错误(核心转储)
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 从C 中的文本提取数字---分割故障
- 分割故障添加了两个表示字符串的大数字
- 根据用户输入计算数组中的可分割数字
- 试图使用递归找到一个数字的所有因子,最终会得到大数字的分割错误
- 如何分割一个二进制字符串来比较每个数字
- 分割一个数字并存储在int数组中