[英]Reading a comma separated file into an integer array
我試圖將包含整數的文本文件讀入整數數組。 如果輸入為:1 3 4 5 6(中間有空格)它工作正常。
但如果輸入是:1,3,4,5,6(逗號分隔)。它只是打印1.(第一個數字)。如果程序發現1,3,4,5,6作為單個實體,那么它應該打印1,3,4,5,6作為第一個指標ryt? 而且File >> x,這個表達式通過檢測兩者之間的空間來逐個取值?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];
int x;
int sum = 0;
ifstream File;
File.open("integer.txt");
if(!File.is_open())
{
cout<<"It failed"<<endl;
return 0;
}
while(File>>x)
{
arr[n] = x;
n++;
}
File.close();
cout<<"n : "<<n<<endl;
for(int i=0;i<n;i++)
{
cout << arr[i] << " ";
}
return 0;
}
這里發生的是在提取第一個字母后,您的代碼嘗試將逗號提取為整數。 因為它無法做到這一點,它將返回false並結束循環。
有一個非常類似的問題在這里 。
你的while循環應該如下所示:
while(File>>x)
{
arr[n] = x;
n++;
if (ss.peek() == ',')
ss.ignore();
}
當你用逗號輸入文件時,它最有可能是將它作為整個字符串讀取。 確保這也是逗號的分隔符,我不知道你將逗號放在這個代碼中的哪個位置,但是你需要一個分隔符。
//example function you can use.
getline( ss, s, ',' )
但如果輸入是:1,3,4,5,6(逗號分隔)。它只是打印1.(第一個數字)。 如果程序找到1,3,4,5,6作為單個實體,那么它應該打印1,3,4,5,6作為第一個索引ryt?
它只打印“1”,因為您嘗試將“1,3,4,5,6”讀入int
對象。 但是, int
不能是“1,3,4,5,6”。 簡單地說,一旦達到第一個“壞”字符(即逗號),解析就會停止,並且最終得到到目前為止已建立的整數,即“1”。
其余的輸入被丟棄。 這就像你的行是“1abcdef”或“1abcdef2345”。
而且File >> x,這個表達式通過檢測兩者之間的空間來逐個取值?
是的,這使得它非常不靈活。
我建議而不是擺弄operator>>
使用std::getline
,傳遞','
作為分隔符。 雖然函數的名稱不再有意義,因為它不再讀取行 (就像使用默認分隔符'\\n'
),它將正常工作。
最后將介紹使用std::stoi
輕松轉換為int
的單個std::string
對象。
當你在它的時候,擺脫raw int arr[100]
並使它成為std::vector<int>
,這樣你就不僅限於100個元素。 無論如何,100是一個丑陋的魔法(任意)數字。
這是一個例子:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
// faking some test file input; behaves like an `std::ifstream`:
std::istringstream is("1,2,3,4,5");
std::vector<int> numbers;
std::string number_as_string;
while (std::getline(is, number_as_string, ','))
{
numbers.push_back(std::stoi(number_as_string));
}
std::cout << "n : " << numbers.size() << "\n";
for(auto&& number : numbers)
{
std::cout << number << "\n";
}
}
正如您所看到的,我還借此機會提出了一些其他優秀的C ++實踐,例如避免using namespace std
和std::endl
。
您是否嘗試過使用ifstream的sscanf? 一個簡單的例子如下
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];
char line[200];
char *ptr=line;
int x=0,count=0;
int sum = 0;
ifstream File;
File.open("integer.txt");
if(!File.is_open())
{
cout<<"It failed"<<endl;
return 0;
}
File.getline(line,200);
while((count=sscanf(ptr,"%d,",&x))>0)
{
arr[n] = x;
n++;
ptr+=count+1;
}
File.close();
cout<<"n : "<<n<<endl;
for(int i=0;i<n;i++)
{
cout << arr[i] << " ";
}
cout<<endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.