什么是逐行读取随机放置字符的简单方法?(C ++)

时间:2013-11-18 14:50:23

标签: c++ input inputstream stdin

sample input

它应该忽略空格并读入2个字符。


我的代码阅读:

#include <iostream>

using namespace std ;

int main(){


char current_char1 ;
char current_char2 ;

//input comes from stdin
while(getc() != '\0'){
     current_char1 = getc() ;
     current_char2 = getc() ;                 
  }      

}

你能说得更简单吗?

3 个答案:

答案 0 :(得分:2)

要从一行读取两个数字,无论空格数如何,这都可以:

std::string line;
std::getline(std::cin, line);

std::istringstream iss(line);

int a, b;
iss >> std::hex >> a >> b;

std::cout << "First value is " << a << ", the second value is " << b << '\n';

答案 1 :(得分:1)

您正在编写C ++,但是stdio.hiostream更容易完成许多任务,而这只是其中之一。

#include <ctype.h>
#include <stdio.h>
#include <string>

using std::string;

// Returns the next two non-`isspace` characters as a std::string.
// If there aren't that many before EOF, returns all that there are.
// Note: line boundaries ('\n') are ignored just like all other whitespace.
string
read_next_two_nonspace(FILE *fp)
{
    string s;
    int c;

    do c = getc(fp);
    while (c != EOF && isspace(c));
    if (c != EOF) s.append(1, c);

    do c = getc(fp);
    while (c != EOF && isspace(c));
    if (c != EOF) s.append(1, c);

    return s;
}

编辑:如果您真正想要的是从面向行的文件中读取两个十六进制数,该文件应该每行有两个这样的数字,并且可能在它们周围有随机数量的空白,那么这是我的首选方法。约阿希姆的方法较短,但不太可靠;特别是,iostreams 不能安全地用于数字输入(!),因为它们是根据scanf来定义的,引发了未定义的行为(!!)数字溢出时。这是更多的代码,但处理任意格式错误的输入。同样,请注意C ++和C库工具的自由混合 - 没有理由不使用旧库,如果它能够满足您的需要,就像在这种情况下一样。

序言:

#include <istream>
#include <stdexcept>
#include <string>
#include <vector>

#include <ctype.h>
#include <errno.h>
#include <stdlib.h>

using std::getline;
using std::invalid_argument;
using std::istream;
using std::vector;
using std::string;

struct two_numbers { unsigned long a; unsigned long b; };

分析器:

#define isspace_or_eol(c) (isspace(c) || (c) == '\0')

// Parse a line consisting of two hexadecimal numbers, separated and surrounded
// by arbitrary whitespace.
two_numbers
parse_line(string const &s)
{
    const char *p;
    char *endp;
    two_numbers val;

    // N.B. strtoul skips *leading* whitespace.
    errno = 0;
    p = s.c_str();
    val.a = strtoul(p, &endp, 16);
    if (endp == p || !isspace_or_eol(*endp) || errno)
        throw invalid_argument("first number is missing, malformed, or too large");

    p = endp;
    val.b = strtoul(p, &endp, 16);
    if (endp == p || !isspace_or_eol(*endp) || errno)
        throw invalid_argument("second number is missing, malformed, or too large");

    // Verify only whitespace after the second number.
    p = endp;
    while (isspace(*p)) p++;
    if (*p != '\0')
        throw invalid_argument("junk on line after second number");

    return val;
}

使用示例:

vector<two_numbers>
read_file(istream &fp, const char *fname)
{
    string line;
    unsigned int lineno = 0;
    vector<two_numbers> contents;
    bool erred = false;

    while (getline(fp, line))
    {
        lineno++;
        try
        {
            contents.append(parse_line(line));
        }
        catch (invalid_argument &e)
        {
            std::cerr << fname << ':' << lineno << ": parse error: " 
                      << e.what() << '\n';
            erred = true;
        }
    }

    if (erred)
        throw invalid_argument("parse errors in file");
    return contents;
}

答案 2 :(得分:-1)

你可以尝试下面的代码,一个基于Zack的

的小修改
#include "stdafx.h"
#include <iostream>

using namespace std;

bool read(FILE * fp, string * ps)
{
    char c = fgetc(fp);

    if(c == EOF)
        return false;

    if(isspace(c))
    {
        ps->clear();
        return read(fp, ps);
    }

    if(isdigit(c))
    {
        ps->append(1, c);
        if(ps->length() == 2)
            return true;
    }

    return read(fp, ps);
}

int _tmain(int argc, _TCHAR* argv[])
{
    FILE * file;
    fopen_s(&file, "YOURFILE", "r");
    string s;
    while(read(file, &s))
    {
        cout<<s.c_str()<<endl;
        s.clear();
    }
    return 0;
}