I am trying to Find lonngest word in sentence - c++

#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
char a[n+1]; // intializing array
cin.getline(a,n); // inputting array
cin.ignore();
int maxlen=0,curr=0,i=0;
while(1)
{
if (a[i] ==' ' || a[i] == '\0'){
maxlen=max(curr,maxlen);
curr=0;
}
curr++;
if (a[i]=='\0'){
break;
}
i++;
}
cout<<maxlen;
}
here i am trying to find the max length of word in this sentence but i am not able to save the sentence or input the array.
To check i put cout for array and its not printing the array i inputed i want to know the reason

error C2131: expression did not evaluate to a constant (6):
This is caused due to using non-standard C++ here:
cin>>n;
char a[n+1]; // intializing array
Arrays in C++ must be declared using a constant expression, not a runtime-based expression. Since n is only known at runtime, this is not legal C++.
As to solving the issue, you don't need raw char arrays. This can easily be done using std::string. In addition, using std::stringstream will make the code even simpler by not having to check for whitespace:
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream>
int main()
{
std::string sentence;
// Read the sentence
std::getline(std::cin, sentence);
// Parse each word
std::stringstream strm(sentence);
std::string word;
size_t maxLen = 0;
while (strm >> word)
maxLen = std::max(maxLen, word.size());
// Output results
std::cout << sentence << "\n" << maxLen;
}
For this input:
This is a test of getting the longest word in a string
the output is:
This is a test of getting the longest word in a string
7
Finally, you should follow a good C++ book instead of going to websites that shows any coding using:
#include<bits/stdc++.h>
or the invalid array syntax mentioned above.
No reputable C++ book, or reputable C++ website that has been peer-reviewed will show code using that header, or the invalid array syntax.
If you go to a website that shows code like this, and the website's purpose is to teach C++, it isn't one you should learn any C++ from.

Related

error: template is declared here. class _LIBCPP_TEMPLATE_VIS basic_stringstream;

I am writing a c++ program to find the number of words in a string using stringstream in c++ but my compiler is giving the above error.
I am using vsCode on my macbook air to do this and using the Xcode's GNU compiler.
I also tried to write the code in the CLION ide which also gives the same error.
Here is the code.
#include <iostream>
using namespace std;
int countWords(string str)
{
// breaking input into word using string stream
stringstream s(str); // Used for breaking words
string word; // to store individual words
int count = 0;
while (s >> word)
count++;
return count;
}
// Driver code
int main()
{
string s = "using stringstream class in cplusplus";
cout << " Number of words are: " << countWords(s);
return 0;
}
Please help me with this.

Making array (char) 1 gives error on stdio.h

I was trying to hold the text entered by user inside an Char array but it does not end up well. I tried this method but i think it deleted after c++ 11.
Here's my code :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
char sentence[2];
cout << "Enter your sentences : ";
gets_s(sentence);
cout << sentence << endl;
system("PAUSE");
return 0;
}
It gives overload error and doesnt works.
Chances are you are trying to get the string literal that is longer than 2 characters yet not being able to insert it into your buffer of:
char sentence[2];
Increase the buffer size to something more acceptable:
char sentence[255];
That being said in C++ you should prefer std::string to character array and std::getline to gets_s.

C++ Cin input to array

I am a beginner in c++ and I want to enter a string as character by character into an array , so that I can implement a reverse function .. However unlike C when the enter is hit a '\n' is not insterted in the stream.. how can I stop data from being entered ?
my code is :
#include<iostream>
#include<array>
#define SIZE 100
using namespace std;
char *reverse(char *s)
{
array<char, SIZE>b;
int c=0;
for(int i =(SIZE-1);i>=0;i--){
b[i] = s[c];
c++;
}
return s;
}
int main()
{
cout<<"Please insert a string"<<endl;
char a[SIZE];
int i=0;
do{
cin>>a[i];
i++;
}while(a[i-1]!= '\0');
reverse(a);
return 0;
}
When you read character by character, it really reads characters, and newline is considered a white-space character.
Also the array will never be terminated as a C-style string, that's not how reading characters work. That means your loop condition is wrong.
To begin with I suggest you start using std::string for your strings. You can still read character by character. To continue you need to actually check what characters you read, and end reading once you read a newline.
Lastly, your reverse function does not work. First of all the loop itself is wrong, secondly you return the pointer to the original string, not the "reversed" array.
To help you with the reading it could be done something like
std::string str;
while (true)
{
char ch;
std::cin >> ch;
if (ch == '\n')
{
break; // End loop
}
str += ch; // Append character to string
}
Do note that not much of this is really needed as shown in the answer by Stack Danny. Even my code above could be simplified while still reading one character at a time.
Since you tagged your question as C++ (and not C) why not actually solve it with the modern C++ headers (that do exactly what you want, are tested, save and work really fast (rather than own functions))?
#include <string>
#include <algorithm>
#include <iostream>
int main(){
std::string str;
std::cout << "Enter a string: ";
std::getline(std::cin, str);
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
output:
Enter a string: Hello Test 4321
1234 tseT olleH

c++ word count(as words we take every possible variable name)

I was asked to make a program that reads a cin could be text and then counts the words in it(i need to count as a word every name that can be accepted as a variable name ex _a,a1) my problem is that my code works for only one byte. if its more than one the sum is always 0.The only thing i think i can have wrong is that i didn't put the string into an array but a friend of mine told me i don't need to do so.below is my code:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main(){
int sum=0;
bool z= false; //z is just a switch to see if we are inside a word\n
string s;
cout<<"Insert text: ";
getline(cin,s); //here we get the string\n
int n=s.length()-1; //for some reason i==(s.length-1) put a warning$
for(int i=0;i==n;i++){ //here we check each byte to see what it contai$
cout<<s[i];
if(isalpha(s[i]) || s[i]=='_'){ //to enter a word we need a let$
z=true;
sum++;}
if(z==true){ // if we are in a word we can have numbers as w$
if(!isalnum(s[i]) && s[i]!='_'){
z=false;}} // exit the current word and go$
if(s[i]==EOF){ // the end\n
break;}}
cout<<"Number of words is: "<<sum<<endl; // the real end\n
return 0;
}
This is so much easier than the code you have provided. We can do this with the STL using an istream iterator. If you choose to use C++ and not C, then you should take advantage of the standard library.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
int main(){
vector<string> words((istream_iterator<string>(cin)), istream_iterator<string>());
for(int i = 0; i < words.size(); i++)
cout << words[i] << '\n';
return 0;
}
Check your for loop.. it runs as long as the second statement is true.. when is it true that i==n? only at the very last byte.. change this to i<=n instead.
First of all you don't need dont use getline because it is insecure, use cin instead. Also you do not need the and use cin instead of getline. Also if getline is used with an array it could pose a serious problem and could be exploited via stack overflow. Sorry I cant help much what you were asking but I just wanted to give you a heads up.

Variable length array of non-POD element type 'string' (aka 'basic_string<char>') c++

I get this error in my c++ code Variable length array of non-POD element type string (aka basic_string<char>).
string words[numWords];
If I get rid of numWords and enter a number this works fine but if i put the same number in a variable it gives me the Variable length array of non-POD element type 'string' (aka 'basic_string<char>') error, I have done it this way before and it worked in visual studio but I have now tried it in Xcode and it doesn't work. I have tried using vectors but I can't get them sot store any data and they just come back blank.
For those who asked this is my vector code should all be there
char ch;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
while(repFile.get(ch))
{
if(ch == ' ' || ch == '\n' || ch == '\t')
{
numWords++;
}
}
vector<string> words (numWords);
while(repFile >> x)
words.push_back(x);
repFile.close();
C++ doesn't have C99-style variable length arrays. Your compiler might support them as an extension, but they're not part of the language. In this specific case, your success with Visual Studio indicates that it does in fact have such an extension. clang++ will support VLAs, but only of POD types, so your attempt to make a VLA of string objects won't work. g++ does work on my machine if I leave off enough warning/error flags.
This initializes words with numWords empty strings then appends the actual strings afterwards:
vector<string> words (numWords);
while(repFile >> x)
words.push_back(x);
Change to:
vector<string> words;
while(repFile >> x)
words.push_back(x);
or:
vector<string> words (numWords);
int idx = 0;
while(repFile >> x /* && idx < numWords */)
words[idx++] = x;
EDIT:
There is no reason to count the number of words before populating the vector:
vector<string> words;
ifstream repFile("//Users//bobthemac//Documents//c++asignment//c++asignment//test1.txt");
if (repFile.is_open())
{
while(repFile >> x)
{
words.push_back(x);
}
repFile.close();
}
Sorry, you need to write gcc --version to get the version.
As others state, you shouldn't use variable-length arrays, but GCC does support them as an extension in C++. My GCC 4.4.4 compiles just fine with the following code:
#include <string>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
string s[n];
return 0;
}
Does that code compile for you? If it does, then you need to give us the smallest piece of code that fails.
The best solution, though, is to use vector<string>.