0

I want to find the longset name of input and its location ,i try but deon`t have any out put can you help me?

#include<iostream> #include<string.h> using namespace std; char longestname(char a[][100] ,int len[] ,int n) { int i; int max = len[0]; for( i=0 ; i<n ; i++) { if(len[i] > max ) max = len[i]; } cout<<"longest name : "<<a[max][100]<<endl; return max; } int main() { int n,i,len[n]; cout<<"enter the number of your students\n"; cin>>n; char a[n][100]; cout<<"enter the name of the students\n"; for( i =0 ; i<n; i++) { cout<<"student["<<i<<"] : "; cin.getline(a[i],100); len[i] = strlen(a[i]); } cout<<"length of the longest name : "<<longestname(a,len,n); }

9th Jun 2021, 7:59 PM
alireza mohammadian
alireza mohammadian - avatar
6 Respostas
+ 3
There are a couple of problems here:- 1) len[] is declared with size of 'n' before the value of 'n' in known. 2) during your first iteration, getline() would read nothing because of stray newline character left by "cin>>n" in input buffer. Fix : declare len[] array after the value of "n" is known and remove that stray newline character from the input buffer before entering the loop ( preferred option is to use cin.ignore() to read and ignore it as you don't need that newline character ) After all the fixes, your code should look like one shared by Abhay That being said, VLA(variable length array) is a C99 feature and is not supported by C++. Although some compilers( including gcc ) support it as an extension, using it in your C++ code is generally considered as a code smell. Better option ( as already suggested by rkk ) is to use an stl alternative ( like std::vector ) to do the job.
10th Jun 2021, 1:13 AM
Arsenic
Arsenic - avatar
+ 2
char a[n][100] Here, n must be a constant declared above with constant value. What you're doing is not supported by some compilers(which is I don't have great ideas of) but if still you want to use dynamic array then have a look at "vectors" STL c++.
9th Jun 2021, 8:28 PM
minirkk
minirkk - avatar
+ 2
Match your code with the following to see the mistakes. https://code.sololearn.com/cPpHux50n4k0/?ref=app You can't declare int len[n] without initializing n first , so do it after you ask an input for n. I honestly can't explain how cin.ignore() works and if you don't use it , your first getline function will be skipped , i.e. it will store first string at a[1] instead of a[0] , but this article might be of some help. https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.tutorialspoint.com/what-is-the-use-of-cin-ignore-in-cplusplus&ved=2ahUKEwjKzdnJs4vxAhXUH7cAHdpgDngQFjAAegQIAxAC&usg=AOvVaw1HF-EeClA2tbk20pqWzVsK&cshid=1623274280616
9th Jun 2021, 9:31 PM
Abhay
Abhay - avatar
0
Thanks I run the code shared by Abay but when the input name long for example" alireza mohammadian siahkalrodi " the code without any out put how to fix this.
10th Jun 2021, 4:35 AM
alireza mohammadian
alireza mohammadian - avatar