[英]Read number from text file without whitespace
我試圖從文本文件中讀取一個12位數字到一個數組。 如果我在每個數字之間放置空格,我就能成功地做到這一點。 例如:
1 1 1 1 1 1 1 1 1 1 1 1
但是當我刪除數字之間的空格時,我的程序不再能夠從文本文件中分配數組。 例如:
111111111111
我確信答案很簡單,但我無法在任何地方找到解決我的確切問題的方法。 下面是我用來分配數組的while循環。
void int_class::allocate_array(std::ifstream& in, const char* file)
{
//open file
in.open(file);
//read file in to array
int i = 0;
while( !in.eof())
{
in >> myarray[i];
i++;
}
in.close();
}
要讀取字符數組,假設沒有空格或其他分隔符,您可以立即從輸入流中讀取整個字符:
in >> myarray;
要創建整數數組,可以通過char讀取輸入char並填充數組:
char c;
int i = 0;
while( !in.eof())
{
in >> c;
myarray[ i++ ] = c - '0';
}
在這種情況下,任何地方都可能有任何數量的空間,它們將被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.