用getchar替换gets的用法

时间:2016-01-28 10:02:48

标签: c getchar gets

我目前有一项家庭作业,我使用了gets。 教授说我应该使用getchar代替。

有什么区别?

如何更改代码以使用getchar?我似乎无法做到这一点。

代码:

#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255

int main() {
  int c;
  char s[STORAGE];

  for(;;) {
    (void) printf("n=%d, s=[%s]\n", c = getword(s), s);
    if (c == -1) break;
  }
}

int getword(char *w) {
  char str[255];
  int i = 0;
  int charCount = 0;

  printf("enter your sentence:\n");   //user input
  gets(str);

  for(i = 0; str[i] != '\0' && str[i] !=EOF; i++){
    if(str[i] != ' '){
      charCount++;
    } else {
      str[i] = '\0'; //Terminate str
      i = -1; //idk what this is even doing?
      break;      //Break out of the for-loop
    }
  }

  printf("your string: '%s' contains %d of letters\n", str, charCount); //output
  strcpy(w, str);

  //    return charCount;
  return strlen(w); //not sure what i should be returning.... they both work
}

1 个答案:

答案 0 :(得分:2)

package ja7; import javax.swing.JFrame; /** * * @author lalit kumar */ public class gframe extends javax.swing.JFrame { /** * Creates new form gframe */ public gframe() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("TRY MAGIC"); setResizable(false); jButton1.setText("cal"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("fing grade "); jButton2.setEnabled(false); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextField1.setEditable(false); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton2) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 111, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(67, 67, 67)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(73, 73, 73) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(143, Short.MAX_VALUE)) ); jButton2.setVisible(false); jTextField1.setVisible(false ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int a,b; int c; a=50; b=56; c=a+b; jTextField2.setText(Integer.toString(c)); jButton2.setEnabled(true); jButton2.setVisible(true ); } private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: int c; c=Integer.parseInt ( jTextField2.getText()) ; jTextField1.setVisible(true ); if(c>50) { jTextField1.setText("A WARD"); } else jTextField1.setText(" B WARD"); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(gframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new gframe().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration } 应该从输入中获取字符串并将其存储到提供的参数中。但是,由于缺乏对输入长度的初步验证,它很容易受到缓冲区溢出的影响。

更好的选择是notnull

但是,使用fgets()部分时,它一次只能读取一个gets()。所以基本上,你必须使用循环逐个读取标准输入,直到你到达一个标记预期输入结束的换行符(或EOF)。

当您读取一个字符(带有可选的验证)时,您可以继续将它们存储在char中,这样,当输入循环结束时,您可以在str中准备好输入字符串。

请勿忘记终止str,以防万一。