计算包括C中的空格在内的整个字符串

时间:2019-01-11 14:17:10

标签: c

我正在尝试建立一个代码,该代码对整个字符串进行计数,并且在找到第一个空格后不会停止。我该怎么办?

我尝试了这种代码,但是它只计算第一个单词,然后显示第一个单词中的字母数。

到目前为止,这是我尝试过的。

TipoDocumento

IF OBJECT_ID('dbo.spInsertCopyDocumentos') IS NOT NULL
DROP PROCEDURE spInsertCopyDocumentos
GO
CREATE PROCEDURE spInsertCopyDocumentos
    @IdArtigo int,
    @IdNovo int
AS
BEGIN
    SET NOCOUNT ON
    -- Optional if you need to check the paramaters if they NULL or not, that's up to you
    INSERT INTO hDocumentos (IdArtigo, 
                             TipoDocumento, 
                             NomeDocumento, 
                             Dados, 
                             Extensao, 
                             Observacoes) --The number of columns specified her must be the same in the select
    SELECT @IdNovo,
           ISNULL(TipoDocumento, <DefaultValue>), -- since it won't accept nulls
           --But since you are selecting from the same table it won't be a problem 
           NomeDocumento,
           Dados, 
           Extensao, 
           Observacoes 
    FROM hDocumentos
    WHERE IdArtigo = @IdArtigo
END

但是仍然会得到与第一个相同的答案。

我希望,如果 输入:狐狸很漂亮。 输出:19

但是我得到的只是 输入:狐狸很漂亮。 输出:3

2 个答案:

答案 0 :(得分:5)

strlen已经包含空格,因为它计算的是字符串的长度,直到终止NUL字符(零,'\0')为止。

您的问题是%s的{​​{1}}转换在遇到空格时会停止读取,因此您的字符串从不包含它(您可以通过打印出该字符串来轻松地进行验证) 。 (您可以通过使用不同的scanf转换来修复它,但是通常,通过scanf进行读取可以更轻松地解决问题–它还会迫使您指定缓冲区大小,从而解决了潜在的缓冲区溢出问题当前代码。)

答案 1 :(得分:2)

Answer by Arkku的诊断正确。 但是,如果您希望使用scanf,则可以执行以下操作:

scanf("%99[^\n]", get);

99告诉scanf读取的字符数不能超过99个,因此您的get缓冲区不会溢出。 [^\n]告诉scanf读取任何字符,直到遇到换行符为止(按回车键时)。

正如Chux指出的那样,该代码仍然存在2个问题。

使用scanf时,最好检查其返回值,这是它可以读取的项目数。同样,使用上述语法时,\n确实保留在输入缓冲区中。因此,您可以这样做:

if(scanf("%99[^\n]", get) == 0){
    get[0] = 0; //Put in a NUL terminator if scanf read nothing
}

getchar();      //Remove the newline character from the input buffer