我有一个包含数字的文字: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;
}
答案 0 :(得分: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);
答案 1 :(得分:0)
#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)
你需要一个布尔变量来声明数字是偶数还是奇数,它也可以通过迭代器解决并检查它是否为%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;
}