howto get with scanf a string ( char * ) from a user input, delimited by double quotes and containing spaces [closed]

StackOverflow https://stackoverflow.com/questions/19760046

  •  03-07-2022
  •  | 
  •  

문제

I am quite noob with c and c++, and I am stucked trying to read a user input delimited between double quotes for a program I have to deliver to my algorithm class. The entry would be in this form: "something like this, with spaces, and delimited by this two double quotes". What I need to get from that is the string ( char * ) contained between the delimiters. Unfortunatelly I have been trying without luck to solve this small issue...

The development environment is a virtualized Windows 7 and the ide (both are requirements from the teacher) is DEVC++

Anyone could give a hint or help me out? I am stucked with this and I am running out of time. thanks in advance!

도움이 되었습니까?

해결책

Assuming you have a stream where the current character is a double quote, you can just

  1. ignore() the current character.
  2. getline() using '"' as the delimiter.

Here is code which skips leading space, verifies that the next character is a '"' and, if so, reads the value into str:

std::string str;
if ((in >> std::ws).peek() == '"' && std::getline(in.ignore(), str, '"')) {
    std::cout << "received \"" << str << "\"\n";
}

다른 팁

If I understood the question correctly, then the following suits you. This approach will eliminate every punctuation.

#include <string>
#include <algorithm>
#include <iostream>

int main ()
{
  std::string input ;
  std::cout << "Please, enter data: ";

  std::getline (std::cin,input);
  input.erase( remove_if(input.begin(), input.end(), &ispunct),  input.end());
  std::cout << input << std::endl;

  std::cin.get();
  return 0;
}

This is the result.

>Please, enter data: There' ?are numerous issues. 
There are numerous issues

This approach is exactly what you are looking for by using strtok

#include <stdio.h>
#include <iostream>

int main() 
{
    char sentence[] = "\"something like this, with spaces, and delimited by this two double quotes\"";  
    char * word;
    std::cout << "Your sentence:\n " << sentence << std::endl;
    word = strtok (sentence,"\"");
    std::cout << "Result:\n " << word << std::endl;

    return 0;
}

The result

Your sentence:
 "something like this, with spaces, and delimited by this two double quotes"
Result:
 something like this, with spaces, and delimited by this two double quotes
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top