Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to code a program based which can compare words of a sentence or paragraph to a database, as if it were a text corrector. My problem here is that I have to enter on the console the text I want to correct as a string and then divide it in words stored in a vector of strings in C++. I tried a thousand ways but I cannot get it done.
Here is the code I last tried:
std::cout << "Enter the text: ";
std::string sentence;
std::vector<std::string> vText;
while (getline(std::cin, sentence)){
std::stringstream w(sentence);
std::string word;
while(w >> word)
vText.push_back(word);
}
When I execute this code, I got nothing, as if the program did nothing. Can you help me please?
This is the final thing (a piece):
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main(){
std::cout << "Introduzca una frase: ";
std::string frase;
std::vector<std::string> vTextoAnalizar;
while (getline(std::cin, frase)){
std::stringstream w(frase);
std::string palabra;
while(w >> palabra)
vTextoAnalizar.push_back(palabra);
}
for (int i=0;i<vTextoAnalizar.size();i++){
std::cout << vTextoAnalizar[i] << std::endl;
}
return 0;
}
Firstly, welcome to stack exchange. Your question has been down voted as you have not made a reasonable effort to ask a good question.
Please take particular note of How to create a Minimal, Complete, and Verifiable example.
I think what you are trying to do is something like this:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> read_text() {
std::cout << "Enter the text: ";
std::string sentence;
std::string word;
std::vector<std::string> vText;
while(getline(std::cin, sentence)){
std::stringstream ss(sentence);
while ( getline( ss, word, ' ' ) ) {
if (word.compare("quit") == 0)
return vText;
vText.push_back(word);
}
}
}
int main() {
std::vector<std::string> test_vector = read_text();
std::cout << "Vector : " << std::endl;
for (int i=0;i<test_vector.size();i++){
std::cout << test_vector[i] << std::endl;
}
}
This will split on spaces, and add your words to the vector at the end of each sentence. I imagine that there are more intelligent ways of parsing, but this should get your test code working.
Hope that helps.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I know some people will say this question is repeated but I really couldn't find a useful answer.
Let's say I have the following program:
#include <iostream>
#include <string>
using std::cout;
int main(){
std::string something;
cout<<"Type something";
std::cin>>something;
}
How can I use setw() so the output will look like this?
Type something "then after some whitespaces for example 10 the user will start typing"
I tried to use setw() in output:
#include <iostream>
#include <string>
#include <iomanip>
using std::cout;
int main(){
std::string something;
cout<<std::left<<std::setw(24)<<"Type something";
std::cin>>something;
}
The expected output was supposed to be:
The actual output is:
I can't reproduce what you say, the code you have showed works fine for me.
#include <iostream>
#include <string>
#include <iomanip>
int main(){
std::string something;
std::cout << std::left << std::setw(24) << "Type something"; // prints "Type something "
std::cin >> something;
return 0;
}
That said, you could simply output a string with the desired number of spaces:
#include <iostream>
#include <string>
int main(){
std::string something;
std::cout << "Type something ";
// alternatively:
// std::cout << "Type something" << std::string(10, ' ');
std::cin >> something;
}
One possible solution might be using any special character after setw
Sample Code:
int main()
{
std::string something;
cout<< "Type something" << setw(24) << ":";
std::cin>>something;
}
Output:
Type something :inputString
References:
iomanip setw() function in C++ with Examples
Setw C++: An Ultimate Guide to Setw Function
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have never used stringstream before and was given a sample code but with no explanation of what was happening in the code. If someone could explain each line's purpose that would be great. I have looked in multiple places but cant seem to pin down the second line.
#include <sstream> // i know this line includes the file
stringstream ss(aStringVariable);// this line in particular
ss >> aVariable;
getline(ss, stringVariable2HoldValue, ‘|’);
There's a constructor for std::stringstream that takes a std::string as a parameter and initializes the stream with that value.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::stringstream ss("foo bar");
std::string str1, str2;
ss >> str1 >> str2;
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
}
This code initializes a stringstream, ss, with the value "foo bar" and then reads it into two strings, str1 and str2, in the same way in which you would read from a file or std::cin.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
My problem sounds like this: I have as a input a huge string with numbers separated by whitespaces. I need to split this string and put the components in a vector and then to use its components. (then to transform to integers bla bla...).
I searched here for this but I did not understand some things entirely, so please a bit of explanation.
Also another question: why the following return one more "Substring: " in the end?
int main()
{
string s("10 20 30 50 2000");
istringstream iss(s);
while (iss)
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
}
system("pause");
return 0;
}
why the following return one more "Substring: " in the end?
Because your loop is broken; you're checking the stream state before reading from it. It's the same problem as described under:
Why is iostream::eof inside a loop condition considered wrong?
First count the amount of whitespaces like this:
int i = counter;
for( size_t i = 0; i < s.size(); ++i )
{
if( ' ' == s[i] )
{
++counter;
}
}
After that you have to substring in another for loop the string s.
Try the following approach
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
int main()
{
std::string s( "10 20 30 50 2000" );
std::istringstream is( s );
std::vector<std::string> v( ( std::istream_iterator<std::string>( is ) ),
std::istream_iterator<std::string>() );
for ( const std::string &t : v ) std::cout << t << std::endl;
return 0;
}
The output is
10
20
30
50
2000
You could initially define the vector as having type std::vector<int> and in the vector initialization use iterator std::istream_iterator<int>.
As for your second question then before outputing a string you have to check whether it was read. So the correct loop will look like
string sub;
while ( iss >> sub )
{
cout << "Substring: " << sub << endl;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to grab ID's from an text file with HTML in it. The ID's are being extracted from URL's in the HTML so I'm looping through the file to find the correct line and then using substrings obtain the correct information. There are two different types of ID so I have two different functions.
The second one (getYearId) works fine, but the first one causes the code to abort on the part that is currently commented out. As you can see, I've tried to output the value of first1 only to find that it's output is alue=", which is part of what I'd assume first was supposed to equal. What am I doing wrong?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;
void getSyllabiId() {
string line;
ifstream myfile("syllabi.txt");
if (myfile.is_open()) {
while (getline(myfile, line)) {
if (line.find("View Assignments") != string::npos) {
string startDel = "syllabusid";
string endDel = "View";
unsigned int first1 = line.find(startDel);
unsigned int last1 = line.find(endDel);
cout << first1 + "\n";
//string syllabusID = line.substr(first1, last1 - first1);
//syllabusID = syllabusID.substr(startDel.size());
// cout << syllabusID + "\n";
}
}
myfile.close();
}
else cout << "Unable to open file.";
}
void getYearId() {
string line;
ifstream myfile("syllabi.txt");
if (myfile.is_open()) {
while (getline(myfile, line)) {
if (line.find("2014-2015</option>") != string::npos) {
string startDel = "value=\"";
string endDel = "\" selected";
unsigned int first = line.find(startDel);
unsigned int last = line.find(endDel);
string yearID = line.substr(first, last - first);
yearID = yearID.substr(startDel.size());
cout << yearID + "\n";
}
}
myfile.close();
}
else cout << "Unable to open file";
}
int main () {
getYearId();
getSyllabiId();
string x;
cin >> x;
return 0;
}
The problem was I never checked to see if first1 and last1 had values, so obviously in one (or several instances) one of them didn't causing the code to abort.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
CODE-JAM 2010 PROBLEM:
Given a list of space separated words, reverse the order of the words.
INPUT:
The first line of input gives the number of cases, N. N test
cases follow.
OUTPUT:
For each test case, output one line containing "Case #x: "
followed by the list of words in reverse order.
Limits:
N <= 5
INPUT:
3
this is a test
foobar
all your base
OUTPUT:
Case #1: test a is this
Case #2: foobar
Case #3: base your all
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
class prog {
char str[50];
public:
void getdata()
{
gets(str);
}
void rev();
void srev();
void display()
{
cout<< str;
}
};
void prog::srev()
{
int i,j,len;
char temp;
len=strlen(str);
for(i=0,j=len-1;i<len/2;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
void prog::rev()
{
int i,k=0;
char word[50];
strcat(str," ");
for(i=0;str[i]!='\0';i++)
{
if(str[i]!=' ')
{
word[k]=str[i];
k++;
}
else
{
while(k>0)
{
cout<<word[--k];
}
cout<<str[i];
}
}
}
void main()
{ clrscr();
fstream file;
int n;
cout<<"\n\n\t";
cin>>n;
prog p[10];
file.open("cj.txt",ios::in|ios::out|ios::binary);
for(int i=0;i<n;i++)
{
cout<<"\n\t";
p[i].getdata();
file.write((char*)&p[i],sizeof(p[i]));
}
file.seekg(0);
for(i=0;i<n;i++)
{
cout<<"\n\n\t";
p[i].srev();
p[i].rev();
}
}
I wrote this program in c++98 version, with turbo 3.0 as the IDE. It worked fine giving the desired ouput in the desired limits.
My question is, as C++ has rolled out C++11 Standard, what changes I have to do in my above code?
Also, can anyone provide me some good links to read out about the exact implementations in the libraries, as the changes must be innumerous, at one place?
For a more idiomatic approach, please see Reversing order of words in a sentence. I modified Stefan's answer a little bit:
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
std::string sentence = "Your sentence which contains ten words, two of them numbers";
std::istringstream stream(sentence);
std::vector<std::string> words;
std::copy(std::istream_iterator<std::string>(stream),
std::istream_iterator<std::string>(),
std::back_inserter(words));
std::reverse(words.begin(), words.end());
for ( size_t i(0); i < words.size(); ++i )
{
std::cout << words[i] << " ";
}
std::cout << "\n";
}
Also, since the problem from what I understand specifies a max amount of letters/words that will be given, you can get rid of std::reverse:
words.resize(20); // replace 20 with max amount
std::copy(std::istream_iterator<std::string>(stream),
std::istream_iterator<std::string>(),
words.rbegin());
Two other contrived examples:
std::reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " "));
std::copy(words.rbegin(), words.rend(), std::ostream_iterator<std::string>(std::cout, " "));
Your code needs considerable revision to follow C++98. At least offhand, I don't see any reason it would need further revision to follow C++11, though you might be able to make the code a little more readable using some of the new features of C++11.
In C++98/03, I'd probably write the code something like this:
int main() {
int num;
std::cin >> num;
for (int i=0; i<num; i++) {
std::string line;
std::getline(line, std::cin);
std::istringstream in(line);
std::vector<std::string> words((std::istream_iterator<std::string>(in)),
std::istream_iterator<std::string>());
std::copy(words.rbegin(), words.rend(),
std::ostream_iterator<std::string>(std::cout, " "));
}
}
In going to C++11, the primary change I'd make would be to use "uniform initialization":
std::vector<std::string> words{std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>()};
A few people have written code to (for one example) use a range-based for loop in cases like this, so the loop would end up something like:
for (auto i : range(0, num))
I guess if you had a lot of other code that could use this, it might be worthwhile, but I see little point in it for one loop.