c++ - 如何跳过每行中的前两个字符以仅将第三个字符分配给 C++ 中的数组

标签 c++

我有一个文本文件如下:
6 1 C
6 2 秒
6 3 R
6 4 R

这只是前四行。其中有 90 个分为 3 个部分,每部分 30 个(6、7 和 8)。我只想将字符读入我的数组。

这是我目前的情况

#include <iostream>
#include <fstream>
using namespace std;

// Global variables
const int MONTHS = 3;
const int DAYS = 30;

// Function definitions
void readFile(char daily[][DAYS], int size);
void showStats(char daily[], int days);

int main()
{

    char daily[MONTHS][DAYS];

    readFile(daily, MONTHS);

    //  Make sure we place the end message on a new line
    cout << endl;

    //  The following is system dependent.  It will only work on Windows
    system("PAUSE");

    /* 
    // A non-system dependent method is below
    char anyKey;
    cout << "Press any key to continue";
    cin >> anyKey;
    */
    return 0;
}

void readFile(char daily[][DAYS], int size)
{
        // open file.
        ifstream inputFile("RainOrShine.dat");
        if (!inputFile)
        {
                cout << "ERROR: cannot find/read file." << endl;
                exit(EXIT_FAILURE);
        }
        cout << "Reading file...\n";

        // read data.
        for (int months = 0; months < size; months++)
        {
                for (int days = 0; days < DAYS; days++)
                {
                  inputFile >> daily[months][days];
                  cout << daily[months][days] << ", ";
                }
                cout << "\nDone with Row[" << (months);
                cout << "]...\n";
        }

        // close file.
        inputFile.close();
        cout << "Closing File...\n" << endl;
}

void showStats(char daily[], int days)
{
     //code
}

目前它正在遍历它并在我的元素的第 1 行中放置 30 个这样的元素: 6, 1, C, 6, 2, S, 6, 3, R, 6, 4, R, 6, 5, C, 6, 6, S, 6, 7, S, 6, 8, S, 6, 9, S, 6, 1, 0,

然后在第二个和第三个中像这样抓取下一组。我应该查看多维数组吗?

非常感谢任何帮助。

最佳答案

如果你只想读第三列,你可以这样做:

std::ifstream infile("thefile.txt");

int dummy1, dummy2;
char c;

std::vector<char> v;

while (infile >> dummy1 >> dummy2 >> c)
{
    std::cout << "We got: '" << c << "'.\n";
    v.push_back(c);
}

关于c++ - 如何跳过每行中的前两个字符以仅将第三个字符分配给 C++ 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16267812/

相关文章:

c++ - 移植项目VS2003 -> VS2013错误C2039 serialize is not member of hash_Map

c++ - Project Euler #3 的这段代码有什么问题?

android - 如何在android中获取堆栈跟踪c++函数名称

c++ - 将图像顺时针旋转 90 度

c++ - 如何从 text.doc 计算数字的总和和平均值

c++ - 什么时候值得使用数据库?

c++ - 编译时符号是#defined,但#ifdef 看不到它

c++ - 指针运算和继承导致未定义的行为

c++ - 未定义的函数引用

android - QWidget vs Qt Quick 用于手机应用程序开发