[英]not able to scan the string with spaces
https://www.codechef.com/problems/LADDU無法掃描代碼第12行上的數組“ work”中的字符串。
#include<stdio.h>
int main()
{
long long int i,j,T,actv,points,a,b,c;
char origin[100],work[100];
scanf("%lld",&T);
while(T--)
{
points=0;
scanf("%lld %s",&actv,origin);
for(i=0;i<actv;i++)
{
printf("hie\n");
scanf("%[^\n]s",work);
printf("hello\n");
}
}
return 0;
}
代替scanf()
使用fgets()
掃描帶空格的字符串。
fgets(work,sizeof(work),stdin);
注意: fgets()
帶有換行符。 所以
size_t n = strlen(work);
if(n>0 && work[n-1] == '\n')
{
work[n-1] = '\0';
}
使用fgets代替scanf。
#define BUFFERSIZE sizeof(work)
if (fgets(work, BUFFERSIZE , stdin) != NULL)
{
// your stuff
}
使您的字符串帶有空格。
如果您的C-stirng小於BUFFERSIZE
,則空終止符前的最后一個字符為' \\n'
scanf("%lld %s",&actv,origin);
執行該行后,換行符仍未使用。
scanf("%[^\\n]s",work);
由於%[^\\n]
不接受換行符,因此不會執行讀取。
(也不需要s
。例如%[^\\n]s
-> %[^\\n]
)
因此,在下面進行更改。
scanf("%lld %s%*c",&actv,origin);
// %*c
跳過一個字符(換行符)或while(getchar()!='\\n');
//跳到換行符
...
scanf("%99[^\\n]%*c",work);
為了快速讀取/寫入數字,請使用:
#include <stdio.h>
void fastRead( size_t *a );
void fastWrite( size_t a );
inline void fastRead(size_t *a)
{
int c=0;
// note: 32 is space character
// consume leading trash
while (c<33) c=getchar_unlocked();
// initialize result value
*a=0;
// punctuation parens, etc are show stoppers
while (c>47 && c <58)
{ // then in range 0...9
*a = (*a)*10 + (size_t)(c-48);
c=getchar_unlocked();
}
//printf( "%s, value: %lu\n", __func__, *a );
} // end function: fastRead
inline void fastWrite(size_t a)
{
char snum[20];
//printf( "%s, %lu\n", __func__, a );
int i=0;
// decompose 'a' into char array
do
{
// 48 is numeric character 0
snum[i++] = (char)((a%10)+(size_t)48);
a=a/10;
}while(a>0);
i=i-1; // correction for overincrement from prior 'while' loop
while(i>=0)
{
putchar_unlocked(snum[i--]);
}
putchar_unlocked('\n');
} // end function: fastWrite
除了上述兩個功能,以下是使用這些功能的典型程序:
#define MAX_VALUE (1000000)
int array[ MAX_VALUE +1 ];
int main( void )
{
// get number of test cases
size_t numTestCases;
fastRead( &numTestCase );
//scanf( "%lu", &numTestCases );
//printf( "%s, Number of Test Cases: %lu\n", __func__, numTestCases);
// accumulate test cases, sorted
for( size_t i=0; i<numTestCases; i++ )
{
size_t value;
fastRead( &value );
//scanf( "%lu", &value );
array[value]++;
}
// output the unique values, assending
for( size_t i=0; i<MAX_VALUE; i++ )
{
if( array[i] )
{
fastWrite( i );
//printf( "%s. %lu\n", __func__, i );
}
}
return 0;
}
fastRead和fastWrite函數(而不是printf和scanf)將大大加快代碼的速度。
現在,您只需要實現問題集。
注意:要讀取字符串:
size_t i = 0;
while( i < sizeof( inputArray ) && (ch = getchar_unlocked()) && ' ' != ch )
{
inputArray[i] = ch;
i++;
}
inputArray[i] = '\0';
您可以使用其他一些字符串定界符,例如'\\ n',而不是''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.