Read input until some characters are encountered

Hi,

I can do this in C, scanf("%s[^.^:^;^\n]", buffer) but I do not know if there is an equivalent input in C++ "cin".

I have checked www.CPlusPlus.com but could not find any in CIn or the <cstring>
could somebody direct me to a site that can explain to me how to do it in C++.

Thanks,
Ed
To do what you expect in C, that conversion specifier has to be %[^.^:;\n] (although repeated ^'s are allowed) not %s[^.^:^;^\n] which reads a word up to the first whitespace. (you probably didn't want to read up to the next ^ either, in which case it is simply %[^.:;\n])

C++ doesn't have stream I/O functions that work with scanf-style scansets, but you could set up a ctype where ., ^, :, ;, and \n are whitespace, but no other characters, and use the usual cin >> buffer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <vector>
#include <locale>
#include <sstream>
 
// This ctype facet classifies .^:;\n but not anything else as whitespace
struct my_whitespace : std::ctype<char> {
    static const mask* make_table()
    {
        // make a copy of the "C" locale table
        static std::vector<mask> v(classic_table(),  classic_table() + table_size);
        // these will be whitespace
        v['.'] |=  space; 
        v['^'] |=  space; 
        v[':'] |=  space; 
        v[';'] |=  space; 
        // space and tab won't be whitespace
        v[' '] &= ~space;
        v['\t'] &= ~space;
        return &v[0];
    }
    my_whitespace(std::size_t refs = 0) :
        std::ctype<char>(make_table(), false, refs) {}
};
 
int main()
{
    std::string in = "a:b.c;d\ne^f";
 
    std::istringstream s(in);
    s.imbue(std::locale(s.getloc(), new my_whitespace()));

    std::string token;
    while(s >> token)
        std::cout << "  " << token<< '\n';
}

online demo: http://ideone.com/DHS28
Last edited on
Cubbi,

My question is if there is an equivalent of scanf("%[^.:;\n]", buffer) in C++ and you answered my question, there is none. Your solution gives me an idea on how to approach the program. Your solution looks OK but I could not quite understand it. so with the idea I got from you I would make my own solution.

Sincerely,

Ed
If you are wanting to just see if there ARE characters (that characters exist), you can do a for loop with an integer. Then add 1 for every line that is greater than nothing. If the integer is greater than 0, there is data, if the interger = 0, then there is no text.
Topic archived. No new replies allowed.