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.